最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node JS - filtering an array - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked Mar 6, 2017 at 15:23 Christian68Christian68 9874 gold badges16 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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)

发布评论

评论列表(0)

  1. 暂无评论