gpt4 book ai didi

Javascript - 如何混合具有特定排序顺序的两个对象数组?

转载 作者:行者123 更新时间:2023-11-28 17:26:57 25 4
gpt4 key购买 nike

我有两个对象数组。像这样的事情:

var arrayA = [
{
type: 'card',
id: 1
},
{
type: 'card',
id: 2
},
{
type: 'card',
id: 3
},
{
type: 'card',
id: 4
},
{
type: 'card',
id: 5
},
];

var arrayB = [
{
type: 'pro-tip',
id: 10
},
{
type: 'pro-tip',
id: 11
},
];

我想合并这两个对象数组,但是按照特定的顺序。基本上,我想要的是,在 arrayA 中的每 N 个元素之后,我想从 arrayB 添加一个元素。如果N == 2最终的数组将如下所示:

var finalArray = [
{
type: 'card',
id: 1
},
{
type: 'card',
id: 2
},
{
type: 'pro-tip',
id: 10
},
{
type: 'card',
id: 3
},
{
type: 'card',
id: 4
},
{
type: 'pro-tip',
id: 11
},
{
type: 'card',
id: 5
},
];

也许做这样的事情并不难,但我正在寻找最优雅的方法来构建一个辅助函数来做到这一点。

<小时/>

编辑:

这是我创建的函数。看起来似乎可行,但可能有一种更简单的方法:

function mergeWithSteps( arrayA, arrayB, nSteps, nElementsToAdd ) {
var finalArray = [],
stepsCount = 0,
elementsToAddCount = 0,
arrayBNumberOfElements = arrayB.length;

arrayA.forEach( function( obj ) {
finalArray.push( obj );
stepsCount++;

if( stepsCount == nSteps && elementsToAddCount < arrayBNumberOfElements ) {
finalArray.push( arrayB[ elementsToAddCount ] );
elementsToAddCount++;
stepsCount = 0;
}
} );

return finalArray;
}

最佳答案

您可以使用Array#slice用于插入想要的项目并从末尾迭代 arrayB,因为每次拼接都会更改插入索引之后的索引。

var arrayA = [{ type: 'card', id: 1 }, { type: 'card', id: 2 }, { type: 'card', id: 3 }, { type: 'card', id: 4 }, { type: 'card', id: 5 }],
arrayB = [{ type: 'pro-tip', id: 10 }, { type: 'pro-tip', id: 11 }],
place = 2,
i = arrayB.length;

while (i) {
arrayA.splice(i * place, 0, arrayB[--i]);
}

console.log(arrayA);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript - 如何混合具有特定排序顺序的两个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51329841/

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