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 .
>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.