I have an array I need to group them based on size_y;
[
{"col":4,"row":1,"size_x":1,"size_y":4},
{"col":2,"row":2,"size_x":1,"size_y":2},
{"col":1,"row":1,"size_x":3,"size_y":1},
{"col":1,"row":4,"size_x":3,"size_y":1},
{"col":1,"row":5,"size_x":4,"size_y":1}
]
Now, if size_y is 4 I want to group all the rows less than or equal to 4.
[
{"col":4,"row":1,"size_x":1,"size_y":4},
{"col":2,"row":2,"size_x":1,"size_y":2},
{"col":1,"row":1,"size_x":3,"size_y":1},
{"col":1,"row":4,"size_x":3,"size_y":1},
],
[
{"col":1,"row":5,"size_x":4,"size_y":1}
]
thanks in advance.
You can use a generator function and .splice()
let arr = [
{"col":4,"row":1,"size_x":1,"size_y":4},
{"col":2,"row":2,"size_x":1,"size_y":2},
{"col":1,"row":1,"size_x":3,"size_y":1},
{"col":1,"row":4,"size_x":3,"size_y":1},
{"col":1,"row":5,"size_x":4,"size_y":1}
];
function* divideBy(a) {
const [copy, [{size_y}] = copy] = [[...a]];
while (copy.length) yield copy.splice(0, size_y);
}
let res = [...divideBy(arr)];
console.log(res)
Using pure JS you can simply do using reduce
let arr = [{"col":4,"row":1,"size_x":1,"size_y":4},{"col":2,"row":2,"size_x":1,"size_y":2},{"col":1,"row":1,"size_x":3,"size_y":1}, {"col":1,"row":4,"size_x":3,"size_y":1},{"col":1,"row":5,"size_x":4,"size_y":1}]
let op = arr.reduce((out,inp)=>{
if(inp.row > 4){
if(out['>4']){
out['>4'].push(inp)
} else {
out['>4'] = [inp]
}
}else{
if(out['<4']){
out['<4'].push(inp)
} else {
out['<4'] = [inp]
}
}
return out
},{})
console.log(Object.values(op))