do you know how to get array like this
[
{
index: 4,
years: [1999, 2001, 2012, 2020, 1999, 1998, 2020],
price: 200
},
{
index: 2,
years: [1999, 2019, 2020],
price: 0
},
{
index: 3,
years: [2020, 1999, 2019, 2020],
price: 100
}
]
with this data
[
{
index: 4,
years: [1999, 1998, 2020],
price: 100
},
{
index: 4,
years: [1999, 2001, 2012, 2020],
price: 200
},
{
index: 2,
years: [1999, 2019, 2020],
price: 0
},
{
index: 3,
years: [1999, 2019, 2020],
price: 0
},
{
index: 3,
years: [2020],
price: 100
}
]
I would like to get the highest price value for the same index and connect the year arrays.
I have no idea how to get such a result.
2
Answers
Collect items with the same index in a map. If an item with a bigger price is found, replace the previous item. If the price is the same merge the years with a set:
I created a custom reducer below that accepts an
accessor
(key or function); areducer
function that takes the existing value, and the current value; and adataArr
(array of item arrays). The first object has priority, so only itsprice
will update.