gpt4 book ai didi

javascript - 识别两个数组之间的删除、附加和前置

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:33:30 26 4
gpt4 key购买 nike

我试图找到两个数组之间的深层差异,如下所示

 var arr = [5,4,6,7,8,9]; var against = [1,2,4,5,6];

那么结果应该是

 appended = [7, 8, 9], prepended = [], removed = [1, 2]

我的逻辑已经用完了,这就是我尝试过的

 var prepend = [];
var append = [];
var removed = [];

var len = against.length;

while (len--) {
var itm = listSplit[len];
if (arr.indexOf(itm) === -1) {
removed.push(len);
} else if (itm < arr[0]) {
// ??
}
}

我怎样才能找到这些值。给我一些逻辑上的想法来找到this .

最佳答案

其中一个解决方案可能是:

var arr = [7,8,9,5,4,6]; 
var against = [1,2,4,5,6];
// make a copy of the original array as appended
var appended = arr;
var removed =[];
var prepended =[];

for(var i=0;i<against.length;i++)
{
//if the element is not present in the original array, add it to removed.
if(appended.indexOf(against[i]) == -1)
{
removed.push(against[i]);
}
else
{
//if it is already present, it was not appended, nor prepended,
//remove it from appended.
appended.splice(appended.indexOf(against[i]),1);
}
}
// one more loop to seperate the prepended from the appended values.
for(var j=0;j<appended.length;j++)
{
if(appended[j] < against[against.length-1])
{
prepended.push(appended.splice(j,1));
j--;
}
}

appended 数组中的最终值将是附加的值,而 removed 中的最终值将是被删除的值。保留的将是前置的。

关于javascript - 识别两个数组之间的删除、附加和前置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25860590/

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