Reputation: 2543
I have two arrays of strings like:
var array = ["one", "two", "three", "six", "twelve", "thirteen", "twenty", "forty", "fifty"]
var array1 = ["on", "t"];
I want to filter array to take out any elements that starts with any of the elements in array1. So after filtering array should look like:
["six", "forty", "fifty"];
I also need to filter array by taking out any elements that have within them any of the elements in array1. So after filtering array should look like:
["six"];
Right now I'm using something like:
_.filter(array, function(n){return _.map(array1, function(m){
return _.startsWith(n, m)})})
which is returning
[[true, false], [false, true], [false, true], [false, false],
[false, true], [false, true], [false, true], [false, false], [false, false]];
Upvotes: 0
Views: 1726
Reputation: 8509
Lo-dash way of solving this problem:
var array1 = ["one", "two", "three", "six", "twelve", "thirteen", "twenty", "forty", "fifty"]
var array2 = ["on", "t"];
var myArray = array1;
_.remove(myArray, function(arr1Elem) {
return _.some(array2, function(arr2Elem) {
return _.includes(arr1Elem, arr2Elem);
});
});
console.log(myArray);
https://jsfiddle.net/a2exvq3r/
Upvotes: 0
Reputation: 2543
I found an answer right before I saw Jonathan M. Thanks for the post you beat me to it. Here's how I did it with LoDash.
_.filter(array, function(n){if (_.contains(_.map(array1, function(m){
return _.startsWith(n, m)}), true)){
} else {
return n;}}));
Upvotes: 0
Reputation: 17461
No lodash needed.
var array1 = ["one", "two", "three", "six", "twelve", "thirteen", "twenty", "forty", "fifty"]
var array2 = ["on", "t"];
array1=array1.filter(function(a){
return array2.every(function(b){
return !a.includes(b)
})
});
filter(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
every(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
includes(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
Upvotes: 2