I have a ``dataset which is an array of objects for some items in a database that has the details of how long it will take in estimatedDays
for a specific item to be shipped:
items : [
{
id: '1'
shippingMethods: [
{
id: 'STANDARD',
estimatedDays: 3,
},
{
id: 'TWODAY',
estimatedDays: 2,
},
{
id: 'NEXTDAY',
estimatedDays: 1,
},
]
},
{
id: '2'
// same shipping data as above but standard shipping will take 4 estimatedDays
},
{
id: '3'
// same shipping data as above but TWODAY shipping will take 3 estimatedDays
},
]
I am wondering if there is a reduce function that could compare each shippingMethod.id
in each item and return a new array back only where shippingMethod.estimatedDays
is greatest compared to all items.
So the end array would be an array of objects with (in this case) 3 shipping methods: STANDARD, TWODAY, and NEXTDAY.
Here you go with the reduce
method,
var items = [ { id: '1', shippingMethods: [ { id: 'STANDARD', estimatedDays: 3 }, { id: 'TWODAY', estimatedDays: 2 }, { id: 'NEXTDAY', estimatedDays: 1 }, ] }, { id: '2', shippingMethods: [ { id: 'STANDARD', estimatedDays: 4 }, { id: 'TWODAY', estimatedDays: 2 }, { id: 'NEXTDAY', estimatedDays: 1 }, ] }, { id: '3', shippingMethods: [ { id: 'STANDARD', estimatedDays: 3 }, { id: 'TWODAY', estimatedDays: 3 }, { id: 'NEXTDAY', estimatedDays: 1 }, ] }, ]; var outItems = items.reduce(function(accu, curr){ if(curr.shippingMethods) { if(accu.length > 0) { for(var i = 0; i < curr.shippingMethods.length; i++) { var current = curr.shippingMethods[i]; if(accu[i].id === current.id && accu[i].estimatedDays < current.estimatedDays) { accu[i] = current; } } } else { accu = curr.shippingMethods; } } return accu; }, []); console.log(outItems);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.