I am having an array with name of the product and its storage
let array = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storage: "256GB"}, {name: "samsung A", storage: "256GB"}]
I have another array which has all the names which needed storage let array be
let array1 = ["samsung A", "samsung B", "samsung C"]
Comparing the above 2 arrays i want to map each key what are the available storages.
I have tried with
array.filter(el => el.name === "samsung A").map(item => item.storage)
But in the above i manually given "samsung A" but i want to get all the storages available in array from all the keys available in array2
3
Answers
A simple approach would be:
To start off, you will need a
storage
map, which maps each device to an array of storage capacities, e.g.{'samsung A': ['128GB', '256GB'] }
.Then, for each product name in
array1
(i.e."samsung A", "samsung B", "samsung C"
), get the correspondingstorage
value(s) inarray
(i.e. filterarray1
to all the keys named after the value on the current iteration and map them to an array).In the end, you add a new entry to the
storage
map which the array returned from the step above.You can also use
.reduce
:As per my understanding