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 badges1 Answer
Reset to default 4You 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)