I want to create an array of objects from an array of objects, this is the data:
// Input:
const shippingMethodOptions = [{
id: 1,
carrier_token: 'fedex',
carrier_name: 'Fedex',
weight: 1,
price: 3
}, {
id: 2,
carrier_token: 'fedex',
carrier_name: 'Fedex',
weight: 2,
price: 6
}, {
id: 3,
carrier_token: 'fedex',
carrier_name: 'Fedex',
weight: 6,
price: 9
}, {
id: 4,
carrier_token: 'usps',
carrier_name: 'Usps',
weight: 6,
price: 9
}, {
id: 5,
carrier_token: 'delaware',
carrier_name: 'Delaware',
weight: 5,
price: 10
}]
As you can see the data has carrier_token and carrier_name, what I want is to create an output array with the unique carriers like so:
// Output:
const carriers = [{
carrier_token: 'fedex',
carrier_name: 'Fedex'
}, {
carrier_token: 'usps',
carrier_name: 'USPS'
}, {
carrier_token: 'delaware',
carrier_name: 'Delaware'
}]
What I have tried is building it with a for loop, however I would love to know if this is possible in a more clean way (reduce?)
This is my current solution so far (but again, I would love to know if it's possible to make it cleaner with Reduce etc.)
const getCarriers = options => {
const carriers = []
options.forEach(({ carrier_token, carrier_name }) => {
const foundIndex = _.findIndex(carriers, carrier => carrier.carrier_token === carrier_token)
if (foundIndex !== -1) {
return
}
carriers.push({
carrier_token,
carrier_name
})
})
return carriers
}
const carriers = getCarriers(shippingMethodOptions)