0

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.

2

2 Answers 2

2

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:

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

Comments

0

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

Comments

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.