-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

2

1 Answer 1

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));
 

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.