如何在UnderScore.js中创建嵌套组

时间:2019-02-03 03:57:28

标签: javascript arrays underscore.js

我有一个数组,需要根据size_y将它们分组;

import 'package:flutter/material.dart';
import 'App.dart';

void main() {
  runApp( MaterialApp(
        home: App(),
  )
    );
}

现在,如果size_y为4,我想将所有小于或等于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}
]

提前谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用生成器函数和.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)

答案 1 :(得分:1)

使用纯JS,您只需使用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))