用lodash过滤两个字符串数组

时间:2015-12-04 18:46:13

标签: javascript arrays lodash

我有两个字符串数组,如:

var array = ["one", "two", "three", "six", "twelve", "thirteen", "twenty", "forty", "fifty"]

var array1 = ["on", "t"];

我想过滤数组以取出任何以array1中的任何元素开头的元素。因此,过滤后的数组应如下所示:

["six", "forty", "fifty"];

我还需要通过取出其中包含array1中任何元素的任何元素来过滤数组。因此,过滤后的数组应如下所示:

["six"];

现在我正在使用类似的东西:

_.filter(array, function(n){return _.map(array1, function(m){
                    return _.startsWith(n, m)})})

正在返回

[[true, false], [false, true], [false, true], [false, false], 
[false, true], [false, true], [false, true], [false, false], [false, false]];

3 个答案:

答案 0 :(得分:2)

不需要lodash。

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)
  })
});

http://jsfiddle.net/pbvLn788/

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

包括():https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

答案 1 :(得分:0)

在我看到Jonathan M.之前我找到了答案。感谢您的帖子,我打败了它。这是我用LoDash做的。

_.filter(array, function(n){if (_.contains(_.map(array1, function(m){
                              return _.startsWith(n, m)}), true)){
                            } else {
                              return n;}}));

答案 2 :(得分:0)

解决这个问题的方法:

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/