gpt4 book ai didi

javascript - 比较javascript中的多维数组

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

我想比较 2 个“多维”数组(数组嵌套在数组中)。

var old_dataArray=new Array(("id-2", "message", "user"), ("id-1", "message", "user"), ("id-0", "message", "user"));
var new_dataArray=new Array(("id-3", "message", "user"), ("id-2", "message", "user"), ("id-1", "message", "user"));

在这种情况下,我想获取仅包含在“old_dataArray”中而不包含在“new_dataArray”中的数组(“id-3”、“message”、“user”)。

我已尝试使用此处介绍的 array_diff 函数。 http://phpjs.org/functions/array_diff:309但它并没有真正起作用!

最佳答案

据我了解,您想获取 new_dataArray 中不在 old_dataArray 中的所有数组,我假设如果每个数组中的第一个元素(“id-n”元素)相同,那么数组的其余部分。您可以这样做:

// create an array to store our results:
var results = new Array();

// loop through new_dataArray:
outerloop:
for (var i = 0; i < new_dataArray.length; ++i) {

// loop through old_dataArray to compare the i'th element
// in new_dataArray with each in old_dataArray:
for (var j = 0; j < old_dataArray.length; ++j) {

// check if the ids are the same
if (new_dataArray[i][0] == old_dataArray[j][0])
// yes it's there, so move on to the next element of new_dataArray
continue outerloop;

}

// if we get here, continue outerloop; was never called so
// this element is not in old_dataArray
results.push(new_dataArray[i]);

}

// now results contains all arrays that are in new_dataArray
// but not in old_dataArray

编辑:但是,如果您希望每个数组中的所有元素都相等,而不仅仅是第一个 (id-n) 元素,请使用:

// create an array to store our results:
var results = new Array();

// loop through new_dataArray:
outerloop:
for (var i = 0; i < new_dataArray.length; ++i) {

// loop through old_dataArray to compare the i'th element
// in new_dataArray with each in old_dataArray:
innerloop:
for (var j = 0; j < old_dataArray.length; ++j) {

// check if the arrays are the same size:
if (new_dataArray[i].length != old_dataArray[j].length)
// no, so they must be different
continue innerloop;

// check if the arrays have the same values
for (var k = 0; k < old_dataArray[j].length; ++k) {

if (new_dataArray[i][k] != old_dataArray[j][k])
// the k'th element is different
continue innerloop;
}

// if we get here, then we have found a match, so move on
continue outerloop;

}

// if we get here, continue outerloop; was never called so
// this element is not in old_dataArray
results.push(new_dataArray[i]);

}

// now results contains all arrays that are in new_dataArray
// but not in old_dataArray

关于javascript - 比较javascript中的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7596934/

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