gpt4 book ai didi

javascript - 如何在 javascript 中将数组中的对象分组为多个数组的 3 个对象集?

转载 作者:行者123 更新时间:2023-11-30 06:25:04 24 4
gpt4 key购买 nike

我有一个如下所示的数组,我还想将其拆分成更小的数组,每个更小的数组都有三个对象,数组中的第一个对象和下两个对象。结果也应该是一个由 3 个对象组的所有数组组成的数组。

var myArray = [
{id: "one", color: "red"},
{id: "two", color: "blue"},
{id: "three", color: "green"},
{id: "four", color: "black"},
{id: "five", color: "red"},
{id: "six", color: "blue"},
{id: "seven", color: "green"},
{id: "eight", color: "black"}
];

我期待这个结果

var myArray = [
[ {id: "one", color: "red"},{id: "two", color: "blue"},{id: "three", color: "green"}],
[ {id: "two", color: "blue"},{id: "three", color: "green"},{id: "four", color: "black"}],
[{id: "three", color: "green"},{id: "four", color: "black"},{id: "five", color: "red"}],
[{id: "four", color: "black"},{id: "five", color: "red"}, {id: "six", color: "blue"}],
[{id: "five", color: "red"}, {id: "six", color: "blue"},{id: "seven", color: "green"}],
[{id: "six", color: "blue"},{id: "seven", color: "green"},{id: "eight", color: "black"}],
];

最佳答案

您可以使用 reduce 函数并使用其索引将三个元素压入新数组

var myArray = [{
id: "one",
color: "red"
},
{
id: "two",
color: "blue"
},
{
id: "three",
color: "green"
},
{
id: "four",
color: "black"
},
{
id: "five",
color: "red"
},
{
id: "six",
color: "blue"
},
{
id: "seven",
color: "green"
},
{
id: "eight",
color: "black"
}
];

let newArray = myArray.reduce(function(acc, curr, index) {
// checking if the index+2 of the array is not out of bound
// element at index,index+1,index+2 , total three elements will be pushed
if (myArray[index + 2] !== undefined) {
let localArray = [];
localArray.push(myArray[index]);
localArray.push(myArray[index + 1])
localArray.push(myArray[index + 2])
acc.push(localArray)
}
return acc;
}, [])

console.log(newArray)

关于javascript - 如何在 javascript 中将数组中的对象分组为多个数组的 3 个对象集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972883/

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