Reputation: 45
so I'm trying to find any way to separate this array based on ID's.
[ [ 1, 123412341234, 2.44 ], [ 1, 123912341234, 23.44 ], [ 1, 623412341234, 82.44 ], [ 2, 123412341234, 22.44 ], [ 2, 123412381234, 2.44 ], [ 2, 723412341234, 29.44 ], [ 3, 123412341234, 24.44 ], [ 3, 123412377234, 34.44 ], [ 3, 520312341234, 54.44 ], [ 4, 123412341234, 12.44 ], [ 4, 938412341234, 19.44 ], [ 4, 603412341234, 10.44 ] ]
weather in separate array or in the same array but with an additional [] around the data with same ID
so this
[
[[ 1, 123412341234, 2.44 ], [ 1, 123912341234, 23.44 ], [ 1, 623412341234, 82.44 ]],
[[ 2, 123412341234, 22.44 ], [ 2, 123412381234, 2.44 ], [ 2, 723412341234, 29.44 ]],
[[ 3, 123412341234, 24.44 ], [ 3, 123412377234, 34.44 ], [ 3, 520312341234, 54.44 ]],
[[ 4, 123412341234, 12.44 ], [ 4, 938412341234, 19.44 ], [ 4, 603412341234, 10.44 ]]
]
or this
[[ 1, 123412341234, 2.44 ], [ 1, 123912341234, 23.44 ]]
[[ 2, 123412341234, 22.44 ], [ 2, 123412381234, 2.44 ], [ 2, 723412341234, 29.44 ]]
[[ 3, 123412341234, 24.44 ], [ 3, 123412377234, 34.44 ], [ 3, 520312341234, 54.44 ]]
[[ 4, 123412341234, 12.44 ], [ 4, 938412341234, 19.44 ], [ 4, 603412341234, 10.44 ]]
This is what I tried to make by myself but it's not working ( the c[i] is not working)
for(let i = 0; i < this.z.length;i++) {
for (let j = 0; j < this.z.length; j++) {
if(this.z[j][0]==i){
this.c[i].push(this.z[j])
}
}
}
Upvotes: 1
Views: 113
Reputation: 108
const array = [
[1, 123412341234, 2.44],
[1, 123912341234, 23.44],
[1, 623412341234, 82.44],
[2, 123412341234, 22.44],
[2, 123412381234, 2.44],
[2, 723412341234, 29.44],
[3, 123412341234, 24.44],
[3, 123412377234, 34.44],
[3, 520312341234, 54.44],
[4, 123412341234, 12.44],
[4, 938412341234, 19.44],
[4, 603412341234, 10.44]
];
let result = [];
for (let id = 0; id < 4; id++) {
result[id] = [];
for (let index = 0; index < array.length; index++) {
if (array[index][0] === id+1) {
result[id].push(array[index]);
}
}
}
console.log(result) ;
Upvotes: 1
Reputation: 386654
You could group the array by checking the predecessor and build a new group for a changing first value of the inner array. This approach needs a sorted array.
const
data = [[1, 123412341234, 2.44], [1, 123912341234, 23.44], [1, 623412341234, 82.44], [2, 123412341234, 22.44], [2, 123412381234, 2.44], [2, 723412341234, 29.44], [3, 123412341234, 24.44], [3, 123412377234, 34.44], [3, 520312341234, 54.44], [4, 123412341234, 12.44], [4, 938412341234, 19.44], [4, 603412341234, 10.44]],
result = data.reduce((r, row, i, a) => {
if (!i || a[i - 1][0] !== row[0]) r.push([]);
r[r.length - 1].push(row);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1