I'm trying to filter an array in javascript, and am struggling when the array is nested.
At the moment, the furthest I've been able to get is filtering a flat array:
var ID = 3
var arr = [{ id : 1, name: "a" }, { id : 2, name: "b" }, { id : 3, name: "c" }]
var result = arr.filter(function( obj ) {return obj.id == ID;});
alert(result[0].name);
Though the above doesn't work if the array looks like this instead:
var arr2 = [
[{ id : 1, name: "a" },{ id : 2, name: "b" }],
[{ id : 3, name: "c" },{ id : 4, name: "d" }]
]
The two examples can be found: https://jsfiddle.net/vjt45xv4/
Any tips for finding the appropriate result on the nested array would be much appreciated.
Thanks!
3 Answers 3
Flatten the array then filter it:
arr.reduce(function(a,b) { return a.concat(b); })
.filter(function(obj) { return obj.id == ID; });
Comments
arr2.filter(function(obj) {
obj.filter(function(d) {
if(d.id == ID) {
result = d;
}
})
});
alert(result.name);
Hope this is what you were looking for. Rather than flattening the data here I went into the nested array till the point where it was flat(and matching) and set the result there.
arr2.forEach(function(d) {
d.forEach(
function(dd){
alert(dd.id);
if (dd.id==ID){
result=dd;
}
}
);
});
alert(result.name);
Edit: As minitech mentioned its same working if just using forEach.
I found this question from perhaps a similar problem:
I have a data structure such as this:
x.suites[0].specs[0].tests[0].results[0].status == "skipped"
My goal was to flag all of the non [skipped/ignored/???] status localed somewhere deep in this structure.
I came up with this solution:
var ignoreStatus = ["skipped"];
x.suites
.forEach( (xsuit)=> { xsuit.specs
.forEach( (xspec)=> { xspec.tests
.forEach( (xtst)=> {
var arry=xtst.results.filter((ftst)=>{
return !ignoreStatus.includes(ftst.status)
});
if(arry.length>0){
console.log(`!!!Flag this:${arry}`)
} else {
console.log("ignored:" ,xtst.results.map(m=>{return m.status}).join("/") );
}
})
})
})
arrto each item inarr2(since items inarr2are arrays themselves)