Organize objects in an array as an array of arrays in JavaScript

I'm attempting to organize a collection of objects into an array of arrays based on the 'group' key in the objects.

Current array:

array =
[
    [{name:’a’,age:’4’,group:’15’},{name:’b’,age:’4’,group:’15’}, 
     {name:’c’,age:’4’,group:’15’}],
    [{name:’aa’,age:’6’,group:’12’},{name:’bb’,age:’6’,group:’12’}],
    [{name:’d’,age:’5’,group:’15’},{name:’e’,age:’5’,group:’15’}, 
     {name:’f’,age:’5’,group:’15’}],
    [{name:’dd’,age:’7’,group:’12’}, 
     {name:’ee’,age:’7’,group:’12’{name:’ff’,age:’7’,group:’12’}]
]

I aim to achieve an array that appears as:

newArray=  [
        {15:[[{name:’a’,age:’4’,group:’15’},{name:’b’,age:’4’,group:’15’}, 
              {name:’c’,age:’4’,group:’15’}],[{name:’d’,age:’5’,group:’15’}, 
              {name:’e’,age:’5’,group:’15’},{name:’f’,age:’5’,group:’15’}]
        },
        {12:[[{name:’aa’,age:’6’,group:’12’},{name:’bb’,age:’6’,group:’12’}],
            [{name:’dd’,age:’7’,group:’12’},{name:’ee’,age:’7’,group:’12’}, 
             {name:’ff’,age:’7’,group:’12’}]]
        }
    ]

Many thanks!

Answer №1

To make arrays flat, you can use the flatten method.
In order to group by group and age, create object maps.
Then, extract individual objects from the object map and convert ages objects into arrays.
As ages are numbers, ES2015 automatically sorts integer indexes, resulting in the data being already sorted by age.

Note: The JavaScript data object provided is not valid JavaScript code due to the use of non-standard single quotes and unclosed brackets. It has been parsed as a string and sanitized to JSON.

res = 
Object.entries(
array.flat().reduce((res,x)=>{
  const {age, group} = x
  res[group] = res[group] || {}
  res[group][age] = res[group][age] || []
  res[group][age].push(x)
  return res
},{})
).map(([k,v])=>({[k]: Object.values(v)}))

console.log(res)
<script>
array =
JSON.parse(`[
    [{name:"a",age:"4",group:"15"},{name:"b",age:"4",group:"15"}, 
     {name:"c",age:"4",group:"15"}],
    [{name:"aa",age:"6",group:"12"},{name:"bb",age:"6",group:"12"}],
    [{name:"d",age:"5",group:"15"},{name:"e",age:"5",group:"15"}, 
     {name:"f",age:"5",group:"15"}],
    [{name:"dd",age:"7",group:"12"}, 
     {name:"ee",age:"7",group:"12"},{name:"ff",age:"7",group:"12"}]
]`.replace(/"/g,"'").replace(/(name|age|group)/g,"'$1'"))
</script>

Answer №2

If you want to achieve a similar result, you can utilize the Reduce method:

array =
[
    [{name:'a',age:'4',group:'15'},
     {name:'b',age:'9',group:'15'}, 
     {name:'c',age:'6',group:'15'},
     {name:'c',age:'8',group:'15'},
     {name:'c',age:'4',group:'15'}],
    [{name:'aa',age:'6',group:'12'}]
];
const groupByAge = (acc, elem)=>{
    acc[elem.age] = acc[elem.age]?  [...acc[elem.age],elem] : [elem];
    return acc
}
var res = array.reduce((acc, elem)=>{
var key = "";
  elem.forEach(k=> {
       key  = k.group;
       acc[k.group] = acc[k.group] ?  [...acc[k.group], k] : [k];
   });
  var temp= acc[key].reduce(groupByAge, {});
  acc[key] = Object.values(temp);
  return acc
},{});

console.log([res])

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

Sorting an object array by date is causing a problem

UPDATE: Finally cracked the code on this issue. I initially assumed that Date was interpreting the date ("29-04-2020") as DD-MM-YYYY, when it should actually be MM-DD-YYYY. For instance, here's an object array I'm working with: let t ...

I need RxJs to return individual elements to the subscriber instead of an array when using http.get

I've been developing an Angular 2 app (RC5) with a NodeJS backend RESTful API integration. One specific route on the backend returns an array of 'Candidates': exports.list = function (req, res, next) { const sort = req.query.sort || null ...

Switching between pages and updating the URL without needing to refresh the page, while still maintaining the content even after a refresh

After experimenting with jQuery's load() method to dynamically change content without refreshing the page, I encountered a recurring issue: the URL remains unchanged. Even when attempting to use history.pushState() to modify the URL, the problem pers ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Remove a div using JavaScript

My approach involves dynamically adding div elements using JavaScript in the following manner: <div id="detail[0]"> <input name="detail.Index" type="hidden" value="0" /> <input name="detail[0].details_name" type="text" /> ...

Can you explain the term used to describe when specific sections of the source code are run during the build process to improve optimization?

One interesting feature I've noticed in next.js is its automatic code optimization during the build process. This means that instead of running the code every time the app is executed, it's evaluated and executed only once during the build. For ...

Issue with resetting Knockout.JS array - unable to make it work

Hey everyone, check out the project I'm currently working on over at Github: https://github.com/joelt11753/Udacity-map In this project, I have a menu generated from a list that can be filtered using an HTML select element. Initially, all items are di ...

AngularJS Multi-select Dropdown Filter Logic

Thank you for taking the time to review my query. Currently, I am working on an AngularJS UI-Grid project where I have incorporated a Multi-select Drop-down Menu for the "First Name" column. However, I am facing challenges in implementing the logic similar ...

Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase. My goal is to consolidate all query results under a single key called this.guestPush. Within my project, there is a multiple select element with different user levels - specifically 4, 6, ...

Invoke functions within a separate function

I am facing an issue when it comes to invoking functions within another function. Below is a snippet of the code I am working with: <script> function saveInfo() { function returnEmail() { var _e = document.getElementById("em ...

How come the data I send gets converted to Undefined when working with Tabulator?

I am currently facing an issue with integrating JSON data as search results into my Tabulator. The goal is to display these search results in their respective columns within the Tabulator. Here is the code snippet I have implemented: <body> <div ...

What steps can be taken to stop the update function from inserting data into MongoDB from a Meteor application

Within my Meteor method, I have implemented a function to check for existing documents. If the document is not found, it gets inserted into the database. However, if it is found during a second attempt, the document is updated and a new one is also inserte ...

To convert an image file into a string, use JSON.stringify before including it in an AJAX request

Is it possible to send image files contained within JSON objects in an array via an AJAX call using JSON.stringify? When attempting to send the data through an AJAX call, and utilizing JSON.stringify with an array containing JSON objects that have image f ...

Check the data from the radio button selection

I am facing an issue with reading the values of radio buttons in a list, all of which have the same id. Despite trying to retrieve the value of each individual radio button, my code only reads the value of the first radio button. <script src="//ajax. ...

Is there a way to get an iframe to mimic the behavior of other media elements within a horizontal scrolling container?

Take a look at this code snippet: $(document).ready(function() { $('.scrollable-area').on('wheel', function(e) { var scrollLeft = $(this).scrollLeft(); var width = $(this).get(0).scrollWidth - $(this).width(); var delta ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

What is the best way to conceal a set of buttons on the main page using vue.js?

I'm having trouble hiding a button-group on the main page. It should disappear when either the button moveTo(0) is clicked or when scrolling to the top of the page. show: function() { this.scrollTop = (window.pageYOffset !== undefined) ? windo ...

My mocks for Jest's readFile and writeFile functions are not being loaded

Just wondering, when using jest.mock(), can I only mock the entire module or can I also mock exported functions and constants? In my app.js file, I am using const fileSystem = require('fs'). I am trying to test an method in the app that reads a f ...

Displaying a div when a button is clicked (PHP)

Hello everyone, I'm new to posting here so please bear with me if I seem inexperienced. On my website, there is a button that needs to disappear when clicked and be replaced by a form without refreshing the page. I was able to accomplish this using ...

Unveiling the Power of KnockoutJS: Displaying HTML Content and Populating

I am trying to achieve a unique effect using KnockoutJS. Let's consider a basic model: var Item = function () { var self = this; self.title = ko.observable(""); }; In addition, I have a ViewModel: var ItemList = function () { var self = ...