简体   繁体   中英

Node JS - filtering an array

I have an array of value (1,2,3) and an array of results (y,n,y). I would like to filter the values based on the results. To that purpose, I'm using the arr.filter capability, as below where I pass arr as the context:

        var arr = ["1","2","3"];
        var res = ["y","n","y"];
        var rarr = res.filter(function(item,index){
          if (item==='y') {
             fRes.push(this[index]);
          };
          return (item==='y');
        },arr);

        console.log(fRes);
        console.log(rarr);

Based on what I see in MDN the doc for array filtering, I'm surprised that rarr does not have the same values as fRes (which is what I'm looking for). My understanding is that the testing is on the values in res and the corresponding item from the context (here arr) is picked if successful. That does not seem to be the case (hence I have this push to construct the table of results I'm looking for)? Thanks - Christian

You can use index , which is second parameter in filter to filter out arr where element with same index in res is y .

 var arr = ["1","2","3"]; var res = ["y","n","y"]; var result = arr.filter(function(e, i) { return res[i] == 'y' }) console.log(result) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM