-3

i have an array with dulipacte values

let myArray=[
    {name: "apple", cost: "10"},
    {name: "apple", cost: "20"},
    {name: "bannana", cost: "10"},
    {name: "mango", cost: "20"},
    {name: "apple", cost: "5"},
    {name: "mango", cost: "50"}
    {name: "orange", cost: "30"}
]

and i want to remove duplicates whose cost is low...expected output to be...

let myArray=[
    {name: "apple", cost: "20"},
    {name: "bannana", cost: "10"},
    {name: "mango", cost: "50"}
    {name: "orange", cost: "30"}
]

Thanks in advance

Tsubasa
  • 1,389
  • 11
  • 21
swati kiran
  • 675
  • 1
  • 4
  • 22

1 Answers1

0

You can use Array.reduce to get the desired result, we create an object / map with a property for each product name.

If the product stored in the map is of a lower cost or does not exist we replace as we enumerate through the list of products.

We then use Object.values to turn back into an array.

let myArray = [
    {name: "apple", cost: "10"},   
    {name: "apple", cost: "20"},
    {name: "bannana", cost: "10"},
    {name: "mango", cost: "20"},
    {name: "apple", cost: "5"},
    {name: "mango", cost: "50"},
    {name: "orange", cost: "30"}
]

let result = myArray.reduce((res, product) => { 
    
    if (!res[product.name]) {
        // The product does not exist in the map, add it
        res[product.name] = product;
    } else if (Number(res[product.name].cost) < Number(product.cost)) { 
        // A cheaper product exists, replace it. 
        res[product.name] = product;
    }
    return res;
}, {});

console.log(Object.values(result));
 
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40