Skip to content
Advertisement

Apply discount on array of object in loop whichever object paid value is higher?

I have array of object which have key paid. I want to apply discount on all objects expect object which paid value is higher using loop.

var booking = [
{id:1,paid:200,currency:'USD'},
{id:2,paid:99,currency:'USD'},
{id:3,paid:100,currency:'USD'},
]

On above array of object name booking i want to make loop and apply discount by adding key discount:true in that object except higher paid value object.

This is what i want after loop

var booking = [
{id:1,paid:200,currency:'USD'},
{id:2,paid:99,currency:'USD',discount:true},
{id:3,paid:100,currency:'USD',discount:true},
]

Advertisement

Answer

You could get max paid value first and then apply the new property, if necessary.

const
    booking = [{ id: 1, paid: 200, currency: 'USD' }, { id: 2, paid: 99, currency: 'USD' }, { id: 3, paid: 100, currency: 'USD' }],
    max = Math.max(...booking.map(({ paid }) => paid)),
    result = booking.map(o => ({ ...o, ...o.paid === max || { discount: true } }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement