gpt4 book ai didi

javascript - 根据每个对象的子项的数量将对象数组拆分为更小的数组

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

我希望在 lodash 中实现类似于 _.chunk() 函数的功能。 chunk 函数根据原始数组中对象的数量将数组分成相等的部分。

但是,我想根据对象子项的数量将 Javascript 数组拆分成更小的数组。所以新数组可以有不同数量的元素,但每个新数组中子项的数量必须总共为 3(如果有余数,最后一个数组除外)。

比如我想用Javascript来转换这个数组:

[ {name:'John', numberOfPets: 5, 
pets:['petOne', 'petTwo', 'petThree', 'petFour', 'petFive']},
{ name:'Andrew', numberOfPets: 5,
pets: ['petSix', 'petSeven', 'petEight', 'petNine', 'petTen']}]

进入这些数组:

[{name: 'John', numberOfPets: 5, pets: ['petOne', 'petTwo', 'petThree']}],

[{name: 'John', numberOfPets: 5, pets: ['petFour', 'petFive']},
{name: 'Andrew', numberOfPets: 5, pets: ['petSix']}],

[{name: 'Andrew', numberOfPets: 5, pets: ['petSeven', 'petEight',
'petNine']}],

[{name: 'Andrew', numberOfPets: 5, pets: ['petTen']}]

你会注意到每个新数组都有 3 个宠物,除了最后一个数组只有 1 个余数。

如有任何帮助,我们将不胜感激。

最佳答案

我认为这是 BeccaGirl 正在寻找的正确轨道。它可能需要一些重构。

var chunks = function(array, size) {
var results = [];
while (array.length) {
results.push(array.splice(0, size));
}
return results;
};

var chunkSize = 3, newArray = [], chunkPets = [];
var oldArray = [ {name:'John', numberOfPets: 5,
pets:['petOne', 'petTwo', 'petThree', 'petFour', 'petFive']},
{ name:'Andrew', numberOfPets: 5,
pets: ['petSix', 'petSeven', 'petEight', 'petNine', 'petTen']}];
var newArray = [];

for(var i=0; i<oldArray.length; i++){
chunkPets = chunks(oldArray[i].pets, chunkSize);
for(var j=0; j<chunkPets.length; j++)
{
if(chunkPets[j].length === chunkSize || i+1 === oldArray.length)
{
newArray.push([{name: oldArray[i].name, numberOfPets: oldArray[i].numberOfPets, pets: chunkPets[j]}]);
}
else{
var tempArray = [];
tempArray.push({name: oldArray[i].name, numberOfPets: oldArray[i].numberOfPets, pets: chunkPets[j]});

if(oldArray.length > i+1){
tempArray.push({name: oldArray[i+1].name, numberOfPets: oldArray[i+1].numberOfPets, pets: oldArray[i+1].pets.splice(0,chunkSize - chunkPets[j].length)});

oldArray[i+1].pets = oldArray[i+1].pets.splice(chunkSize -chunkPets[j].length-1,oldArray[i+1].pets.length);
newArray.push(tempArray);
}
}
}
}

console.log(newArray);

关于javascript - 根据每个对象的子项的数量将对象数组拆分为更小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48831604/

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