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

后端 未结 8 1057
抹茶落季
抹茶落季 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: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);
    }
    

提交回复
热议问题