I have searched stackoverflow for answers but I do not really see anything which solves this. I want to take an objects in an array, match them by their name. Then calculate the total of the matching objects hours value.
If this is the array
var arr = [{name: 'Apple', hours: 6}, {name: 'Nokia', hours: 8},
{name: 'Apple', hours: 4}, {name: 'Nokia', hours: 12},];
//return [{name: 'Apple', totalHrs: '10'}], [{name: 'Nokia', totalHrs:
'24'}]
Thank you for any help.
That's not possible, an object literal can't have two identical keys. Instead you could sum the values and take the name as a key
let arr = [{name: 'Apple',hours: 6}, {name: 'Nokia',hours: 8},{name: 'Apple',hours: 4}, {name: 'Nokia',hours: 12}]; let obj = arr.reduce((a, b) => { a[b.name]= (a[b.name] || 0) + b.hours; return a; }, {}); console.log(obj);
Use some hashing and for loop
var hash={}; // hash array to contain names and total hours
var arr = [{name: 'Apple', hours: 6}, {name: 'Nokia', hours: 8},
{name: 'Apple', hours: 4}, {name: 'Nokia', hours: 12},];
for(var i=0; i<arr.length; i++)
{
if(arr[i].name in hash)
hash[arr[i].name]+=arr[i].hours;
else
hash[arr[i].name]=arr[i].hours;
}
console.log(hash);`
You can do this:
function findItemsByProp(array, propName, value) {
var results = [];
for (var i = 0; i < array.length; i++) {
if (array[i][propName] == value)
results.push(array[i]);
}
return results;
}
This is how to use it:
var matching = findItemsByProp(myArray, 'name', 'someValueOfNameProp');
var total = 0;
for(var i = 0; i < matching.length; i++)
total += matching[i].hours;
console.log(total);
of course you can do the sum while iterating over the array, but this is a general method to be used any where else.
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.