首页 > 解决方案 > 如何将数组中的对象分组为javascript中多个数组的3个对象?

问题描述

我有一个如下的数组,我想进一步拆分成更小的数组,每个更小的数组都有三个对象,数组中的第一个和接下来的两个对象。结果也应该是一个由 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"}],
    ];

标签: javascriptnode.js

解决方案


Array#reduce您可以使用and解决此问题Array#slice

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"}
]

const output = myArray.slice(0, myArray.length - 2)
                      .reduce((r, _, i) => 
                          [...r, myArray.slice(i, i + 3)]
                      , [])

console.log(JSON.stringify(output))

使用范围的替代方法

我相信这是解决您的问题的好方法,因为它不涉及操作源数组,而只是准备一个数组数组,其中每个内部数组包含以下 3 个元素的索引myArray

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"}
]

// Creates a numeric array containing numbers
// starting from 'start'  to 'end'. It's zero-indexed!
const range = ( start, end ) => {
   const result = []
   
   for(let i = start; i < end; i++) result.push(i)
   
   return result
}


const output = range ( 0, myArray.length - 2 )
                     .map( i => range ( i, i + 3 ).map ( j => myArray[j] ) )


console.log ( JSON.stringify ( output ) )


推荐阅读