How to Create Nested Group By in UnderScore.js

2019-06-11 17:35发布

问题:

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.

回答1:

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)



回答2:

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