Got an array of arrays like this:
let arr = [
[
{"key":2, "other":123},
{"key":2, "other":222}
],
[
{"key":3, "other":0}
],
[
{"key":1, "other":11},
{"key":1, "other":23}
],
[
{"key":1, "other":22}
]
]
I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:
let arr = [
[
{"key":2, "other":123},
{"key":2, "other":222}
],
[
{"key":3, "other":0}
],
[
[
{"key":1, "other":11},
{"key":1, "other":23}
],
[
{"key":1, "other":22}
]
],
]
I tried to use reduce function, but the result was totally different.
let final = []
for (let i=0; i<arr.length; i++) {
let arr1 = i==0?arr:arr.slice(i)
let final1 = arr1.reduce((acc,x)=> {
acc = acc[0].key==x[0].key?acc.concat(x):acc
return acc
})
arr1.length>1&&final.push(final1)
}
In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?
[{ key: 1, count: 2 }, ...]?