javascript - 如何将数组中的对象分组为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"}],
];
解决方案
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 ) )
推荐阅读
- c++ - С++ sfml 如何在鼠标的帮助下绘制形状
- html - 在嵌套的 json 中注册一个角度形式
- c - 为什么 Node *root 中没有更新?
- pandas - 如何在 python pandas 中使用字符串匹配和聚合函数有效地合并 csv
- flutter - 颤振中的谷歌地图视图
- bash - 带有“let”的 Bash 分配因“/”而失败
- ssas - 从时间维度获取度量的 LastNonEmpty 值
- linux - Prometheus Docker - 连接到外部机器
- c# - 如何让 C# DateTime 显示非美国日期
- java - Log4j2 Slf4j 问题 - 在服务器启动时未创建记录器文件