NodeJS – 从数组中减去数组,不删除所有重复项
标题可能没有多大意义,但是你将如何做这样的事情:
a = [1, 2, 2, 3, 3, 3]; b = [1, 2, 3]; a.subtract(b);
我想这个返回[2,3,3],而不是[]类似的问题的其他答案会,只保留不在其他数组中的项目,而不是只删除有多less其他arrays。
你可以创build一个Array
的原型,并通过检查和消除find的元素来过滤数组。
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));
您可以使用filter()
和indexOf()
来检查元素是否存在于其他数组中,如果使用了splice()
var a = [1, 2, 2, 3, 3, 3]; var b = [1, 2, 3]; var result = a.filter(function(e) { let i = b.indexOf(e) return i == -1 ? true : (b.splice(i, 1), false) }) console.log(result)
这里有一种方法可以做到这一点:循环访问数组b
并检查它是否存在于数组a
。 如果是这样,在其索引处插入一个undefined
的。 返回a
数组过滤去除所有undefined
元素。
编辑:实际上不需要filter使用splice()
有其他人做的。
let a = [1, 2, 2, 3, 3, 3]; let b = [1, 2, 3]; let sub = function(a, b) { for (i in b) { let index = a.indexOf(b[i]); if (index != -1) { a.splice([index],1) } } return a } console.log(sub(a, b))
这里的答案build议使用indexOf()
来检查是否存在效率低的O(n ^ 2)运行时。 更有效的方法是使用一个Map
并用has()
检查是否存在,将运行时降到O(n):
// see the bottom of the answer for a more efficient implementation than this Object.defineProperty(Array.prototype, 'subtract', { configurable: true, value: function subtract (array) { return this.filter( function (element) { const count = this.get(element) if (count > 0) { this.set(element, count - 1) } return count === 0 }, array.reduce( (map, element) => { if (map.has(element)) { map.set(element, map.get(element) + 1) } else { map.set(element, 1) } return map }, new Map() ) ) }, writable: true }) let a = [1, 2, 2, 3, 3, 3] let b = [1, 2, 3] console.log(a.subtract(b))