gpt4 book ai didi

javascript - 将带有对象的数组拆分为 2 个数组

转载 作者:行者123 更新时间:2023-11-29 11:00:01 26 4
gpt4 key购买 nike

我有一个包含多个对象的数组。我想将此数组拆分为多个数组。拆分的条件是 continent 项。

MyArray = [{continent:"europe", fruit:"orange", value:2},
{continent:"asia", fruit:"banana", value:2},
{continent:"europe", fruit:"apple", value:2},
{continent:"asia", fruit:"apple", value:5}
];

输出:

[
[{continent:"europe", fruit:"orange", value:2},
{continent:"europe", fruit:"apple" value:2}
], [
{continent:"asia", fruit:"banana", value:2},
{continent:"asia", fruit:"apple" value:5}]
];

最佳答案

您可以搜索具有相同大陆的数组并更新此数组或使用实际对象推送一个新数组。

var array = [{ continent: "europe", fruit: "orange", value: 2 }, { continent: "asia", fruit: "banana", value: 2 }, { continent: "europe", fruit: "apple", value: 2 }, { continent: "asia", fruit: "apple", value: 5 }],
grouped = array.reduce(function (r, o) {
var group = r.find(([{ continent }]) => continent === o.continent)
if (group) {
group.push(o);
} else {
r.push([o]);
}
return r;
}, []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将带有对象的数组拆分为 2 个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48974820/

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