javascript 删除另一个数组中包含的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19957348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all elements contained in another array
提问by Tap
I am looking for an efficient way to remove all elements from a javascript array if they are present in another array.
我正在寻找一种有效的方法来从 javascript 数组中删除所有元素,如果它们存在于另一个数组中。
// If I have this array:
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
// and this one:
var toRemove = ['b', 'c', 'g'];
I want to operate on myArray to leave it in this state: ['a', 'd', 'e', 'f']
我想对 myArray 进行操作以使其处于这种状态: ['a', 'd', 'e', 'f']
With jQuery, I'm using grep()
and inArray()
, which works well:
使用 jQuery,我使用grep()
and inArray()
,效果很好:
myArray = $.grep(myArray, function(value) {
return $.inArray(value, toRemove) < 0;
});
Is there a pure javascript way to do this without looping and splicing?
有没有一种纯 javascript 的方式来做到这一点而无需循环和拼接?
回答by Sirko
Use the Array.filter()
method:
使用Array.filter()
方法:
myArray = myArray.filter( function( el ) {
return toRemove.indexOf( el ) < 0;
} );
Small improvement, as browser support for Array.includes()
has increased:
小改进,因为浏览器支持Array.includes()
增加:
myArray = myArray.filter( function( el ) {
return !toRemove.includes( el );
} );
Next adaptation using arrow functions:
使用箭头函数的下一个适应:
myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );
回答by Ashwin Balamohan
The filter
method should do the trick:
该filter
方法应该可以解决问题:
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = ['b', 'c', 'g'];
// ES5 syntax
const filteredArray = myArray.filter(function(x) {
return toRemove.indexOf(x) < 0;
});
If your toRemove
array is large, this sort of lookup pattern can be inefficient. It would be more performant to create a map so that lookups are O(1)
rather than O(n)
.
如果您的toRemove
数组很大,这种查找模式可能效率低下。创建地图以便查找O(1)
而不是O(n)
.
const toRemoveMap = toRemove.reduce(
function(memo, item) {
memo[item] = memo[item] || true;
return memo;
},
{} // initialize an empty object
);
const filteredArray = myArray.filter(function (x) {
return toRemoveMap[x];
});
// or, if you want to use ES6-style arrow syntax:
const toRemoveMap = toRemove.reduce((memo, item) => ({
...memo,
[item]: true
}), {});
const filteredArray = myArray.filter(x => toRemoveMap[x]);
回答by Deepak Acharya
If you are using an array of objects. Then the below code should do the magic, where an object property will be the criteria to remove duplicate items.
如果您使用的是对象数组。那么下面的代码应该可以发挥作用,其中对象属性将是删除重复项的标准。
In the below example, duplicates have been removed comparing name of each item.
在下面的示例中,已删除重复项比较每个项目的名称。
Try this example. http://jsfiddle.net/deepak7641/zLj133rh/
试试这个例子。http://jsfiddle.net/deepak7641/zLj133rh/
var myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'chirag', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chandan', place: 'mumbai'}
];
var toRemove = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'}
];
for( var i=myArray.length - 1; i>=0; i--){
for( var j=0; j<toRemove.length; j++){
if(myArray[i] && (myArray[i].name === toRemove[j].name)){
myArray.splice(i, 1);
}
}
}
alert(JSON.stringify(myArray));
回答by Crenshinibon
Lodash has an utility function for this as well: https://lodash.com/docs#difference
Lodash 也有一个实用功能:https://lodash.com/docs#difference
回答by Benny Neugebauer
ECMAScript 6 setscan be used for computing the different elements of two arrays:
ECMAScript 6 集合可用于计算两个数组的不同元素:
const myArray = new Set(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
const toRemove = new Set(['b', 'c', 'g']);
const difference = new Set([...myArray].filter((x) => !toRemove.has(x)));
console.log(Array.from(difference)); // ["a", "d", "e", "f"]
回答by user2582833
I just implemented as:
我刚刚实施为:
Array.prototype.exclude = function(list){
return this.filter(function(el){return list.indexOf(el)<0;})
}
Use as:
用于:
myArray.exclude(toRemove);
回答by MarcoL
If you cannot use new ES5 stuff such filter
I think you're stuck with two loops:
如果你不能使用新的 ES5 东西,filter
我认为你会陷入两个循环:
for( var i =myArray.length - 1; i>=0; i--){
for( var j=0; j<toRemove.length; j++){
if(myArray[i] === toRemove[j]){
myArray.splice(i, 1);
}
}
}
回答by mojtaba roohi
var myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'chirag', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chandan', place: 'mumbai'}
];
var toRemove = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'}
];
myArray = myArray.filter(ar => !toRemove.find(rm => (rm.name === ar.name && ar.place === rm.place) ))
回答by Matas Vaitkevicius
Now in one-liner flavor:
现在是单线口味:
console.log(['a', 'b', 'c', 'd', 'e', 'f', 'g'].filter(x => !~['b', 'c', 'g'].indexOf(x)))
Might not work on old browsers.
可能不适用于旧浏览器。
回答by Craciun Ciprian
You can use _.differenceByfrom lodash
您可以使用_.differenceBy从lodash
const myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'chirag', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chandan', place: 'mumbai'}
];
const toRemove = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'}
];
const sorted = _.differenceBy(myArray, toRemove, 'name');
Example code here: CodePen
示例代码在这里:CodePen