[英]How to group every 2nd and 3rd items of an array into sub-arrays?
I have an array of objects我有一个对象数组
const objects = [a, b, c, d, e, f, g ... ]
and I want them to turn into我希望他们变成
const result = [a, [b, c], d, [e, f], g ... ]
Any ideas?有任何想法吗?
[Edit] My apologies. [编辑] 我的歉意。 This is my first post, didn't know I have to show my attempts.这是我的第一篇文章,不知道我必须展示我的尝试。 I don't think I deserve the mean comments either, be nice people.我也不认为我应该受到刻薄的评论,做个好人。 I solved it after a head-banging 4 hours.我在令人头疼的 4 小时后解决了它。 Here is my solution:这是我的解决方案:
const result = []
const method = array => {
for (let i = 0; i < array.length; i += 3) {
const set = new Set([array[i + 1], array[i + 2]])
if (i !== array.length - 1) {
result.push(array[i])
result.push(Array.from(set))
} else {
result.push(array[i])
}
}
}
Thanks for the responses guys!谢谢你们的回应! I read every single one of them.我阅读了其中的每一本书。
You could take a while loop and push either an item or a pair of items.您可以进行 while 循环并推送一个项目或一对项目。
var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g'], grouped = [], i = 0; while (i < array.length) { grouped.push(array[i++]); if (i >= array.length) break; grouped.push(array.slice(i, i += 2)); } console.log(grouped);
You can do this with plain for
loop and %
modulo operator.您可以使用普通的for
循环和%
modulo 运算符来做到这一点。
const objects = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] const result = [] for(let i = 0; i < objects.length; i++) { if(i % 3 === 0) { const arr = objects.slice(i + 1, i + 3) result.push(objects[i]) if(arr.length) result.push(arr) } } console.log(result)
this is my solution:这是我的解决方案:
const objects = ["a", "b", "c", "d", "e", "f", "g"];
let result = [];
let toGroup = false;
for(let i = 0; i < objects.length ; i++){
if(toGroup){
result.push([objects[i], objects[++i]]);
}
else result.push(objects[i]);
toGroup = !toGroup;
}
this has a particular case that you have not specified, where it doesn't work, for example if inside objects
there are 2 elements, and so i don't know what you would like to do in that case这有一个你没有指定的特殊情况,它不起作用,例如,如果内部objects
有 2 个元素,所以我不知道在这种情况下你想做什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.