Skip to content
Advertisement

Javascript reduce() on array of objects, with entries being simple variables and array as well

I’m trying to use the reduce function in order to iterate through an array of objects and to get an output summing up the data shown inside of the array of objects (a kind of duplicate remover in fact).

On data such as :

JavaScript

when using the function :

JavaScript

It will fork fine if I call this getValues function getValues(mainData, "color") for the color key, giving the following output : ["red", "green"], which is expected.

But if i call the function with getValues(mainData, "type"), this function will ignore most of the values from the array type value from the key type.

I tried to solve it by using a for loop limited by data["type"].length just before the if...else condition of the reduce function, like this :

JavaScript

But it does not work either.

Anyone has an idea of how to solve this ?

Advertisement

Answer

you can use flatMap for that

like this

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement