[英]How to group every 2nd and 3rd items of an array into sub-arrays?
我有一個對象數組
const objects = [a, b, c, d, e, f, g ... ]
我希望他們變成
const result = [a, [b, c], d, [e, f], g ... ]
有任何想法嗎?
[編輯] 我的歉意。 這是我的第一篇文章,不知道我必須展示我的嘗試。 我也不認為我應該受到刻薄的評論,做個好人。 我在令人頭疼的 4 小時后解決了它。 這是我的解決方案:
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])
}
}
}
謝謝你們的回應! 我閱讀了其中的每一本書。
您可以進行 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);
您可以使用普通的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)
這是我的解決方案:
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;
}
這有一個你沒有指定的特殊情況,它不起作用,例如,如果內部objects
有 2 個元素,所以我不知道在這種情況下你想做什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.