How do I pass an extra parameter to the callback function in Javascript .filter() method?

后端 未结 8 1018
抹茶落季
抹茶落季 2020-12-22 16:31

I want to compare each string in an Array with a given string. My current implementation is:

function startsWith(element) {
    return element.indexOf(wordTo         


        
相关标签:
8条回答
  • 2020-12-22 16:40

    There is an easy way to use the filter function, access all params, and not over complicate it.

    Unless the callback's thisArg is set to another scope filter does not create its own scope, and we can access params within the current scope. We can set 'this' to define a different scope in order to access other values if needed, but by default it is set to the scope it's called from. You can see this being used for Angular scopes in this stack.

    Using indexOf is defeating the purpose of filter, and adding more overhead. Filter is already going through the array, so why do we need to iterate through it again? We can instead make it a simple pure function.

    Here's a use-case scenario within a React class method where the state has an array called items, and by using filter we can check the existing state:

    checkList = (item) => {  // we can access this param and globals within filter
      var result = this.state.filter(value => value === item); // returns array of matching items
    
      result.length ? return `${item} exists` : this.setState({
        items: items.push(item) // bad practice, but to keep it light
      });
    }
    
    0 讨论(0)
  • 2020-12-22 16:51

    For those looking for an ES6 alternative using arrow functions, you can do the following.

    let startsWith = wordToCompare => (element, index, array) => {
      return element.indexOf(wordToCompare) === 0;
    }
    
    // where word would be your argument
    let result = addressBook.filter(startsWith("word"));
    

    Updated version using includes:

    const startsWith = wordToCompare => (element, index, array) => {
      return element.includes(wordToCompare);
    }
    
    0 讨论(0)
  • 2020-12-22 16:52

    The second parameter of filter will set this inside of the callback.

    arr.filter(callback[, thisArg])
    

    So you could do something like:

    function startsWith(element) {
        return element.indexOf(this) === 0;
    }
    addressBook.filter(startsWith, wordToCompare);
    
    0 讨论(0)
  • 2020-12-22 16:55

    For anyone wondering why their fat arrow function is ignoring [, thisArg], e.g. why

    ["DOG", "CAT", "DOG"].filter(animal => animal === this, "DOG") returns []

    it's because this inside those arrow functions are bound when the function is created and are set to the value of this in the broader encompassing scope, so the thisArg argument is ignored. I got around this pretty easily by declaring a new variable in a parent scope:

    let bestPet = "DOG"; ["DOG", "CAT", "DOG"].filter(animal => animal === bestPet); => ["DOG", "DOG"]

    Here is a link to some more reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this

    0 讨论(0)
  • 2020-12-22 16:55

    based on oddRaven answer and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

    i did it 2 different way . 1) using function way . 2) using inline way .

    //Here  is sample codes : 
    
    var templateList   = [
    { name: "name1", index: 1, dimension: 1 }  ,
    { name: "name2", index: 2, dimension: 1 }  ,
    { name: "name3", index: 3, dimension: 2 }  ];
    
    
    //Method 1) using function : 
    
    function getDimension1(obj) {
                    if (obj.dimension === 1) // This is hardcoded . 
                        return true;
                    else return false;
                } 
    
    var tl = templateList.filter(getDimension1); // it will return 2 results. 1st and 2nd objects. 
    console.log(tl) ;
    
    //Method 2) using inline way 
    var tl3 = templateList.filter(element => element.index === 1 || element.dimension === 2  ); 
    // it will return 1st and 3rd objects 
    console.log(tl3) ;

    0 讨论(0)
  • 2020-12-22 16:58
    function startsWith(element, wordToCompare) {
        return element.indexOf(wordToCompare) === 0;
    }
    
    // ...
    var word = "SOMETHING";
    
    addressBook.filter(function(element){
        return startsWith(element, word);
    });
    
    0 讨论(0)
提交回复
热议问题