Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Group array of objects into 2D arrays based on nested value

I have an array of objects like this

array1 = [{data: ..., name: a}, {data: ..., name: b}, {data: ..., name: a}, {data: ..., name: c}, {data: ..., name: c}, {data: ..., name: b}]

I want to sort it in such a way that it groups them by name in sub-arrays

array2 = [
  [{data: ..., name: a}, {data: ..., name: a}, {data: ..., name: a}],
  [{data: ..., name: b}, {data: ..., name: b}],
  [{data: ..., name: c}]
]

I don't always know what the name will be, so I can not manually do 'if name === 'a' etc.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use Array.reduce() here to group your data by name. We create an object with a property for each name present, appending any matching value to an array at this value. We'd then used Object.values() to create our desired array.

array1 = [{data: {}, name: 'a' }, {data: {}, name: 'b'}, {data: {}, name: 'a'}, {data: {}, name: 'c'}, {data: {}, name: 'c'}, {data: {}, name: 'b'}];

const grouped = Object.values(array1.reduce((acc, cur) => { 
    acc[cur.name] = [...(acc[cur.name] || []), cur];
    return acc;
}, {}));

console.log('Grouped:', grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

Please try the below code

let objMap = {};
array1.map(arr=>{
 if(!objMap[arr.name]){
  objMap[arr.name]=[]
 }
 objMap[arr.name].push(arr)
})
console.log(Object.values(objMap));

about 4 years ago · Juan Pablo Isaza Report

0

Actually this is grouping not sorting.

This can be done with a looping technique. I use Array.reduce here

const array1 = [{ data: 'some value', name: 'a' }, { data: 'some value', name: 'b' }, { data: 'some value', name: 'a' }, { data: 'some value', name: 'c' }, { data: 'some value', name: 'c' }, { data: 'some value', name: 'b' }];
const array2 = array1.reduce((acc, curr) => {
  const node = acc.find(item => item.find(subItem => subItem.name === curr.name));
  if(node) {
    node.push(curr)
  } else {
    acc.push([curr])
  }
  return acc;
}, []);
console.log(array2);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!