Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group the second elements of multiple nested arrays based on first element in javascript?

The first Array is something like this :

let firstArray = [[0,2], [1,3], [0,5], [2,8], [1,4], [3,2]];

I want to merge the nested arrays that has the same first element and use that first element as index in the new built array ; the resulted array should be something like this:

secondArray = [[2,5], [3,4], [8], [2]]

what is the best way to achieve this in javascript .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can reduce your array to produce the desired result like this

let firstArray = [[0,2], [1,3], [0,5], [2,8], [1,4], [4,2]];

const secondArray = firstArray.reduce((acc, [ idx, val ]) => {
  acc[idx] = acc[idx] ?? [] // initialise to an empty array
  acc[idx].push(val) // add the value
  return acc
}, []).filter(Boolean) // filter skipped indices

console.log(JSON.stringify(secondArray))

I’ve added in a filter to remove skipped indices.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading