1

Input array

[{ id: 1, title: 'shirt', price: 2000 }, 
{ id: 2, title: 'shirt', price: 4000}, 
{ id: 3,  title: 'tshirt', price: 10000}]

Expected output

[{ id: 1, title: 'shirt', price: 6000 },          // 2000 + 4000
{ id: 3,  title: 'tshirt', price: 10000}]

Have tried multiple ways to achieve but couldn't get a solution.

I'm able to get unique objects but need the addition of price as well

let result = products.filter((product, index, self) =>
  index === self.findIndex((t) => (t.title === product.title))
)
console.log(result);
2
  • what about id? should it take the first one? Commented Nov 7, 2020 at 17:36
  • @NinaScholz yeah duplicate price should add to the first matched. Commented Nov 7, 2020 at 17:37

1 Answer 1

1

You could take an object as hash bale for same title and get the values from the object.

const
    data = [{ id: 1, title: 'shirt', price: 2000 }, { id: 2, title: 'shirt', price: 4000}, { id: 3,  title: 'tshirt', price: 10000}],
    result = Object.values(data.reduce((r, o) => {
        if (r[o.title]) r[o.title].price += o.price;
        else r[o.title] = { ...o };
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

Thanks, Really it solved my problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.