简体   繁体   English

从数组lodash中删除项目

[英]Remove item from array lodash

i've two array and I want to remove entries that exist in array 2 from array 1 我有两个数组,我想从数组1中删除数组2中存在的条目

of course I can loop and create new array but my question is if lodash have some util that can help … 当然,我可以循环并创建新的数组,但是我的问题是lodash是否有一些实用程序可以帮助……

var array1 = [“user1”,”user2", “user3", “user4”];


var array2 = [“user1”, “user3"];

I want that array1 will have after the remove 我想要删除后的array1

var array1 =[”user2", “user4”];

I saw that lodash have this but is there is better way ? 我看到lodash有这个功能,但是还有更好的方法吗?

var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});

With lodash you can use _.difference(array, [values]) Where array is the array to inspect, and [values] are the values to exclude. 使用lodash可以使用_.difference(array, [values])其中array是要检查的数组,而[values]是要排除的值。

Check documentation at https://lodash.com/docs/4.17.4#difference https://lodash.com/docs/4.17.4#difference上查看文档

var array1 = ['user1', 'user2', 'user3', 'user4'];
var array2 = ['user2', 'user4'];

array1 = _.difference(array1, array2); //['user1','user3'];

If you are looking for a vanilla JS solution, you can concat your two arrays and filter out duplicated items: 如果您正在寻找普通的JS解决方案,则可以合并两个数组并过滤出重复项:

 var array1 = ['user1', 'user2', 'user3', 'user4']; var array2 = ['user1', 'user3']; array1 = [...array1, ...array2].filter((e, i, self) => self.indexOf(e) === self.lastIndexOf(e)); console.log(array1); 

If you cannot use ES6 spread operator (...) , use array.prototype.concat : 如果您不能使用ES6 spread operator (...) ,请使用array.prototype.concat

 var array1 = ['user1', 'user2', 'user3', 'user4']; var array2 = ['user1', 'user3']; array1 = array1.concat(array2).filter((e, i, self) => self.indexOf(e) === self.lastIndexOf(e)); console.log(array1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM