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


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.

0

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