2

比较两个 javascript 数组并创建两个包含缺失元素和新元素的新数组的最有效方法是什么?数组元素将始终是字符串或数字,并且不能 100% 确定它们会以任何方式排序。

var old_array = ['11', '13', '14', '18', '22', '23', '25'];
var new_array = ['11', '13', '15', '16', '17', '23', '25', '31'];
var missing_elements = [];
var new_elements = [];

/*
* some magic goes here
* which compares
* new_array with old_array
*/

console.log(missing_elements); // would produce ['14', '18', '22']
console.log(new_elements); // would produce ['15', '16', '17', '31']

非常感谢!

4

3 回答 3

3

Drew Noakes 解决方案的代码:

var old_array = ['11', '13', '14', '18', '22', '23', '25'];
var new_array = ['11', '13', '15', '16', '17', '23', '25', '31'];
var missing_elements = _.difference(old_array, new_array);
var new_elements = _.difference(new_array, old_array);

console.log(missing_elements); // would produce ['14', '18', '22']
console.log(new_elements); // would produce ['15', '16', '17', '31']
于 2012-12-19T21:55:03.760 回答
2

我会使用 Underscore.js 的交集差分函数。

于 2012-12-19T21:40:53.587 回答
0

排序将是最有效的(假设您没有任何其他先决条件来进行优化):

var old_array_sorted = old_array.slice().sort(); // slicing for not mutating
var new_array_sorted = new_array.slice().sort(); // the original array

for (var o=0, n=0; o<old_array_sorted.length && n<new_array_sorted.length; ) {
    if (old_array_sorted[o] < new_array_sorted[n])
        missing_elements.push ( old_array_sorted[o++] );
    else if (old_array_sorted[o] > new_array_sorted[n])
        new_elements.push( new_array_sorted[n++] );
    else
        n++, o++;
}
[].push.apply(missing_elements, old_array_sorted.slice(o));
[].push.apply(new_elements, new_array_sorted.slice(n));
于 2012-12-19T21:44:50.447 回答