标题可能没有多大意义,但你会如何做这样的事情:
a = [1, 2, 2, 3, 3, 3];
b = [1, 2, 3];
a.subtract(b);
我希望它返回 [2, 3, 3],而不是像类似问题的其他答案那样返回 [],它只保留根本不在其他数组中的项目,而不是只删除多少个在另一个数组中。
最佳答案
您可以为数组
创建原型(prototype),并通过检查和消除找到的元素来过滤数组。
Array.prototype.subtract = function (array) {
array = array.slice();
return this.filter(function (a) {
var p = array.indexOf(a);
if (p === -1) {
return true;
}
array.splice(p, 1);
});
}
var a = [1, 2, 2, 3, 3, 3],
b = [1, 2, 3];
console.log(a.subtract(b));
带有哈希表的更快版本:
Array.prototype.subtract = function (array) {
var hash = Object.create(null);
array.forEach(function (a) {
hash[a] = (hash[a] || 0) + 1;
});
return this.filter(function (a) {
return !hash[a] || (hash[a]--, false);
});
}
var a = [1, 2, 2, 3, 3, 3],
b = [1, 2, 3];
console.log(a.subtract(b));
关于javascript - NodeJS - 从数组中减去数组,而不是删除所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46016990/