i've two array and I want to remove entries that exist in array 2 from array 1
of course I can loop and create new array but my question is if lodash have some util that can help …
var array1 = [“user1”,”user2", “user3", “user4”];
var array2 = [“user1”, “user3"];
I want that array1 will have after the remove
var array1 =[”user2", “user4”];
I saw that lodash have this but is there is better way ?
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.
Check documentation at 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:
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
:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.