In my data structure, I have a list of deliveries that includes different cities and the number of units delivered to each city:
var deliveries = [{
location: "Chicago",
units: 10
}, {
location: "San Francisco",
units: 5
}, {
location: "Miami",
units: 2
}, {
location: "San Francisco",
units: 13
}, {
location: "San Francisco",
units: 2
}, {
location: "Chicago",
units: 16
}, {
location: "Miami",
units: 1
}];
I want to be able to query any city in the list and retrieve the number of times it appears along with the total units delivered to that city. The code I currently use for this purpose is:
function getData(arr, city) {
var numberOfdeliveries = 0;
var totalUnitsDelivered = 0;
arr.forEach(function(val, index, arr) {
if (val.location === city) {
numberOfdeliveries += 1;
totalUnitsDelivered += val.units
}
})
return "number of deliveries: " + numberOfdeliveries + ". Total units:" + totalUnitsDelivered
}
getData(deliveries, "San Francisco"); // number of deliveries: 3. Total units:20
This function works accurately.
However, I am interested in exploring if using reduce can provide an array containing all cities with their respective delivery counts and total units. The desired output should resemble:
[{
"Chicago": 2,
units: 26
}, {
"San Francisco":20,
units: 5
}, {
"Miami": 2,
units: 3
}];
Thus far, my attempts have resulted in an object displaying only the count of appearances of each city:
var deliveries = [{
location: "Chicago",
units: 10
}, {
location: "San Francisco",
units: 5
}, {
location: "Miami",
units: 2
}, {
location: "San Francisco",
units: 13
}, {
location: "San Francisco",
units: 2
}, {
location: "Chicago",
units: 16
}, {
location: "Miami",
units: 1
}];
var answer = deliveries.reduce(function(obj, val, index, all) {
if (!obj[val.location]) {
obj[val.location] = 1
} else {
obj[val.location]++
}
return obj
}, {})
console.log(answer); //{ Chicago: 2, 'San Francisco': 3, Miami: 2 }