gpt4 book ai didi

javascript - 如何在 UnderScore.js 中创建嵌套分组依据

转载 作者:行者123 更新时间:2023-11-28 17:10:43 27 4
gpt4 key购买 nike

我有一个数组,我需要根据 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}
]

现在,如果 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}
]

提前致谢。

最佳答案

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

关于javascript - 如何在 UnderScore.js 中创建嵌套分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499832/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com