Transform an array of objects into a two-dimensional array to organize elements by their identical ids in typescript

I have a collection of objects:

arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2, name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'}];

I am looking to transform the array into a two-dimensional array based on the catid property (essentially grouping elements with the same catid together):

arr2 = [[{catid: 1, name: 'mango', category: 'fruit'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'} ],[{catid: 2, name: 'potato', category: 'veg'}],[{catid: 3, name: 'chicken', category: 'nonveg'}]]

How can I achieve this in typescript or javascript?

Answer №1

If you want to achieve this, you can utilize the Object.groupBy() method:

const arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2, name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'}];

const result = Object.values(Object.groupBy(arr1, item => item.catid));
console.log(JSON.stringify(result));

An alternative approach is using the Array#reduce() function:

Playground

const arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2, name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'}];

const result = arr1.reduce((r, item) => 
    ((r.map.get(item.catid)?.push(item) ?? r.map.set(item.catid, r.arr[r.arr.length] = [item])), r), 
    {map: new Map<typeof arr1[number]['catid'], typeof arr1[number][]>, arr: new Array<typeof arr1>}).arr;

console.log(JSON.stringify(result));

Answer №2

To achieve the same outcome, one can opt for using a for loop:

      // Sorting arrays by 'catid'
        const arr1 = [
            {catid: 1, name: 'mango', category: 'fruit'},
            {catid: 2, name: 'potato', category: 'veg'},
            {catid: 3, name: 'chicken', category: 'nonveg'},
            {catid: 1, name: 'apple', category: 'fruit'},
            {catid: 1, name: 'banana', category: 'fruit'}
        ];

        const result = {};

        for(var {catid, name, category} of arr1) {
            if(!result[catid]) result[catid] = [];
            result[catid].push({ catid, name, category });
        }

        console.log(JSON.stringify({"Sorted Data": result},null,2));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

Importing a JavaScript file into another JavaScript file as text in React Native can be a convenient way

In my project, I have a file named MyFirstPage.js that contains the following code snippet: renderCards() { let icon = this.state.icon; .... .... .... } This code is responsible for rendering cards within the main render function. However, as the ...

How come the splice method is changing the value of the original object?

There's something strange happening with this code I'm trying out. Code: const x = [{ a: 'alpha', b: 'beta' }, { a: 'gamma' }]; const y = x[0]; y.a = 'delta'; x.splice(1, 0, y) console.log(x) Output: [ ...

How can nunjucks templates be accessed from NPM (node modules)?

Is there a solution to make nunjucks imports/includes resolve from the NPM node_modules directory? Let's say we have installed a package as follows: npm i -S @example/cards Now, we need to import from it in a template like this: {% import "@exampl ...

Ensuring that toggleClass is consistently displayed for all visitors to the website

Is there a way to make toggleClass save and remain for all visitors of the site? Although I tried, this method appears to be not working: https://jsfiddle.net/715j94gL/3/ $(function(){ $(".worker").click(function(){ $(this).toggle ...

JavaScript: iterating over an array of objects containing nested arrays

Within my leaflet project, I created a function that accepts an array containing objects, each of which holds an array of markers and an ID to distinguish the group. Here is the sample array: var markerGroupArray = [ { features: [L.marker([39.61, -105.02 ...

The error message "domElement" cannot be modified because it is read-only in the THREE.WebGLRenderer

I encountered an issue while attempting to initialize the WebGLRenderer: (Some unnecessary lines have been omitted) import * as THREE from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48544e5 ...

Utilizing JSON to generate cxf-wadl2java mappings

After receiving a specification of a RESTful service in json format, I am tasked with creating a Java API library for the client. Although Swagger can handle this task effortlessly, my preference is to utilize the cxf-wadl2java Maven plugin. However, it s ...

What are the steps to preview a video using AngularJS?

I have a unique feature in my Angular.js application that allows users to upload various types of files, including documents, images, and videos. While I have successfully implemented the functionality to upload any type of file, I am now looking to find ...

Interrogating a multi-dimensional array using the MongoDB C# driver

Here is how my document is structured: "ID" : "fruit1", "Keys" : [ ["apple", "carrot"] ["banana"] ] I am trying to query for Keys = "carrot" using MongoDB C# driver. Can anyone help with this? When I tried in shell, this ...

Issues with the initial calculator project I built using JavaScript (excluding HTML and CSS)

My first calculator is nearly complete, but I have encountered a challenge. The functionality of my calculator is quite simple; it prompts the user for input using window.prompt and performs addition, subtraction, multiplication, or division based on the u ...

JQuery is displaying the word "undefined" instead of the expected JSON array values

Currently, I'm in the process of developing a PhoneGap application that utilizes JQuery and AJAX to interact with JSON data from a PHP file. Specifically, there's a part of my app where I want users to click a button and have it display a list of ...

System.Net.WebException: Connection error: ConnectFailure (Connection refused)

I'm facing an issue with connecting my Xamarin page to a PHP script in order to insert user data into a MySQL database using JSON. Unfortunately, I encountered a connection failure with the following error: System.Net.WebException: Error: ConnectFa ...

What is the best way to retrieve a document from a collection in a Meteor application?

My experience with mongodb is very limited, so I need help on how to retrieve a document from a meteor collection. I am trying to check if a document exists for the user and update it with an object. if (Saves.find({_id: Meteor.userId()}).fetc ...

Instructions on retrieving the index of an element from an array utilizing the Arrays.asList method

In my Android project, I have created an array called "people" using a different class "Person" for each element: people = new Person[]{ new Person("Python"), new Person("PHP"), new Person("Pascol"), new Pe ...

Can Vue.js be paired with pure Node.js as a backend without relying on Express?

After successfully building a project with both vue js and node js, specifically with express, I'm curious if it's feasible to solely utilize node js without frameworks like express. ...

Tips for arranging multiple arrays based on the order of the first array

Let's say I have multiple arrays. $a = array("E", "A", NULL, "D", "C"); $b = array("Dog","Cat","Horse","Bear","Zebra"); $c = array(12, 11, 20, 30, 19); The first array is not necessarily numeric and may contain nulls. I am looking to sort all three ...

Toggle visibility (individually duplicating) one thousand sentences while maintaining optimal browser and host performance

I have created JQuery scripts to toggle the display of future sentences on my page (approximately 1000 duplicates) and I am seeking the most efficient method (for browser/host) to accomplish this task. Here are two functional solutions that I have already ...

Working with Dynamic JSON Parsing in C#

I have encountered a challenging task while working with an API that utilizes GraphQL to return JSON data. Instead of mapping the entire service structure into C# data structures (.NET types/classes), I aim to dynamically deserialize the JSON content. In ...