Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Filter Nested Arrays

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!

like image 417
Steve Avatar asked Sep 14 '15 18:09

Steve


People also ask

How to access nested array object in JavaScript?

You can access a nested array of objects either using dot notation or bracket notation. JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of an object. Both arrays and objects expose a key -> value structure.


2 Answers

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.

like image 67
hunters30 Avatar answered Oct 06 '22 20:10

hunters30


Flatten the array then filter it:

arr.reduce(function(a,b) { return a.concat(b);  })
   .filter(function(obj) { return obj.id == ID; });
like image 24
John Strickler Avatar answered Oct 06 '22 19:10

John Strickler