dbj44
dbj44

Reputation: 1998

How to filter an array of objects by property?

Given the following array, which contains arrays of objects:

[
  [
    {color: blue, size: 3},
    {color: red, size: 1},
    {color: blue, size: 4}
  ],
  [
    {color: blue, size: 4},
    {color: green, size: 9},
    {color: gren, size: 3}
  ]
]

How could I filter the data so that I am only left with objects which have a proprty of blue, like this:

[
  [
    {color: blue, size: 3},
    {color: blue, size: 4}
  ],
  [
    {color: blue, size: 4}
  ]
]

It is in the context of D3js, but this maybe just a plain JavaScript question.

Upvotes: 0

Views: 118

Answers (2)

nnnnnn
nnnnnn

Reputation: 150040

Here's one way:

outputArray = inputArray.map(function(a) {
                return a.filter(function(el) { return el.color === "blue"; });
              });

The .map() method creates a new array whose elements will be the result of calling the function you provide for each element in the original array. (If you want to overwrite the original array, just assign the result back to the same variable instead of to a new one.)

The .filter() method creates a new array with just the elements from the original which pass the test in the function you pass it.

Further reading:

Upvotes: 2

Juan Davila
Juan Davila

Reputation: 39

You could iterate through the array with if-else statement for the color blue with a loop.

Upvotes: 0

Related Questions