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

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

提交回复
热议问题