Javascript .filter() 数组使用另一个数组的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7353917/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:57:00  来源:igfitidea点击:

.filter() array using another array's elements

javascriptarraysfilter

提问by firedrawndagger

I have an array of people's names along with their knowledge of languages. What I want to do is pass a filter onto the language column and filter out any results that don't match.

我有一系列人的名字以及他们的语言知识。我想要做的是将过滤器传递到语言列并过滤掉任何不匹配的结果。

This is the sample array

这是样本数组

   var myArray = [["Steppen", "Spanish Polish"],
                  ["Wolf", "Spanish Polish Tagalog"],
                  ["Amanda", "Spanish"],
                  ["Ada", "Polish"],
                  ["Rhonda", "Spanish Tagalog"]];

As far as passing in filters, it could be either one language or many. Even if one language from a filter matches - the result should be returned. So for example, a filter of "Tagalog" should return - Wolf and Rhonda. A filter of "Spanish Polish" should return everyone - there's either a match in Spanish or Polish.

至于传入过滤器,它可以是一种语言或多种语言。即使过滤器中的一种语言匹配 - 也应该返回结果。因此,例如,应返回“他加禄语”过滤器 - Wolf 和 Rhonda。“西班牙语波兰语”的过滤器应该返回每个人 - 有西班牙语或波兰语的匹配项。

I wrote the filter function but for some reason it's getting stuck, when I pass the filter "Tagalog" it only iterates to the second cell in the array (Spanish Polish Tagalog) and repeats itself multiple times instead of going forward.

我编写了过滤器函数,但由于某种原因它卡住了,当我通过过滤器“他加禄语”时,它只迭代到数组中的第二个单元格(西班牙语波兰语他加禄语)并重复多次而不是前进。

What am I doing wrong, should I be iterating differently?

我做错了什么,我应该以不同的方式迭代吗?

 var userPassedFilter = new Array();
 userPassedFilter[0] = "Tagalog";

 newArray = consolidatedFilters(myArray, userPassedFilter);
 console.log(newArray);

 function consolidatedFilters(passedArray, passedFilter)
 {
 var filteredArray = passedArray.filter(    
    function(el)
    {
        for (var i = 0; i < passedArray.length; i++)
         {
            console.log("i is " + i);
             for (var j in passedFilter)
            {
                console.log("Passed Filter j " + passedFilter[j]);
                console.log("Passed Array  i " + passedArray[i][1]);        
                console.log("String Search " + passedArray[i][1].search(passedFilter[j]));

                if (passedArray[i][1].search(passedFilter[j]) != -1)
                {
                    return true;
                }
            }           
        }
         return false;
    }
 );     
 return filteredArray;
 }

回答by pimvdb

To me it seems like you're making it a little too complicated.

对我来说,你似乎让它有点太复杂了。

  1. Iterating three times (filter, forloop, for inloop).
  2. Using a for inloop for an array.
  3. Using both new Arrayand [...].
  1. 迭代 3 次 ( filter,for循环,for in循环)。
  2. for in对数组使用循环。
  3. 使用new Array[...]

I updated it a little and it looks like this is what you want: http://jsfiddle.net/pimvdb/RQ6an/.

我更新了一点,看起来这就是你想要的:http: //jsfiddle.net/pimvdb/RQ6an/

var myArray = [["Steppen", "Spanish Polish"],
              ["Wolf", "Spanish Polish Tagalog"],
              ["Amanda", "Spanish"],
              ["Ada", "Polish"],
              ["Rhonda", "Spanish Tagalog"]];

var userPassedFilter = ["Tagalog"];

newArray = consolidatedFilters(myArray, userPassedFilter);
console.log(newArray);

function consolidatedFilters(passedArray, passedFilter) {
    var filteredArray = passedArray.filter(
    function(el) { // executed for each person
        for (var i = 0; i < passedFilter.length; i++) { // iterate over filter
            if (el[1].indexOf(passedFilter[i]) != -1) {
                return true; // if this person knows this language
            }
        }
        return false;
    }
    );     
    return filteredArray;
}

回答by Debabrata Nayak

this is the ultimate solution in the ES6 way: No need to Search the same query again in another thread.

这是 ES6 方式的终极解决方案: 无需在另一个线程中再次搜索相同的查询。

var array1 = ['a', 'b', 'c', 'd', 'e'];
var array2 = ['b', 'd', 'f'];

array1 = array1.filter(function(item) {
  return !array2.includes(item); 
})
console.log(array1); // [ 'a', 'c', 'e' ]
console.log(array2); // [ 'b', 'd', 'f' ]

回答by millerjay

here is a more generic version that removes all elements that are in the filter array

这是一个更通用的版本,它删除了过滤器数组中的所有元素

function destroyer(arr) {
  // Remove all the values
  var passedArray = arr;
  var passedFilter = Array.prototype.slice.call(arguments, 1);

  var newArray = passedArray.filter(function(x){
    if(passedFilter.indexOf(x) !== -1){
      return false;
    }
    return true;
  });

  return newArray;
}


destroyer([1, 2, 3, 1, 2, 3], 3, 2);
//prints [1,1]

回答by DonBale

I'm new to javascript and this is the only way I was able to filter an array with another array which made sense to me:

我是 javascript 新手,这是我能够用另一个对我有意义的数组过滤数组的唯一方法:

function filterThisByThis(arr) {
var numArgs = arguments.length; 
var newArr = [];
for (var i = 1; i < numArgs; i ++) {
newArr.push(arguments[i]); 
} // makes a new array from all arguments parsed to fuction minus the orginal array 
arr = arr.filter(function(val) {
  for (var j = 0; j < newArr.length; j++) {
   if (val == newArr[j]) {
      return false;}
  }
  return true;
  }); // uses the filter function to iterate over the orginal array taking out all values which occur in the new array 
return arr;
}  
filterThisByThis([1, 2, 3, 4, 1, 2, 3, 4], 1, 3);
// prints [2, 4, 2, 4]

回答by sixstarpro

Another answer to @millerjay response

@millerjay 回复的另一个答案

function destroyer(arr) {
    var array = arr;
    var filterArray = Array.from(arguments).slice(1);
    var filtered = arr.filter(function(val){
        return filterArray.indexOf(val) === -1;
    });
    return filtered;
}

destroyer([1, 2, 3, 1, 2, 3], 3, 2);
//prints [1,1]