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

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - looking at things differently helps :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.