Home > Mobile >  how can I filter the nth element of an array located inside of another array?
how can I filter the nth element of an array located inside of another array?

Time:10-02

I need to filter the data I am using in a D3 line chart. My data (caled 'slices') is an array of 8 object, each objet has two keys ('id' and 'values'), the value of the key 'values' is another array of 46 objects data structure

My question is, how can I filter the nth element of 'values'?

what I can do is :

slices.filter(function(d,i){return i%3 == 1})

but this is filtering every 3 elemets of the top level, I get 3 results because there are only 8 elements, I dont want this. I want to filter every 3 elements in 'values' (all the 46 objects arrays)

CodePudding user response:

As commented, you will have to use:

slices.map(
  ({id, values}) => ({
    id,
    values: values.filter((_, i) => i%3===1)
  })
)

Now why this:

Your data structure looks like:

[{
  id: "",
  values: [...]
}]

and when you say how can I filter the nth element of 'values'?, it essentially means you need all values in slices to have updated value for values.

So you will have to follow these steps:

  1. Loop over slices and return processed values
  2. In the loop, create new object that needs to be returned.
  3. Filter values based on your logic
  4. Set this value to values property of returned value
  • Related