0

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.

3
  • You cannot have an object with two name and two totalHrs properties. Commented Jan 9, 2018 at 20:19
  • What have you tried? StackOverflow is not a code-writing service, it's here to help you identify and fix problems with code you have already written Commented Jan 9, 2018 at 20:19
  • Sorry about that, my bad. I edited return. I meant I wanted 2 arrays. I can loop through and get total for one name at a time, but not both names. I will look into underscore or lodash. Commented Jan 9, 2018 at 20:25

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I see now where I was messing up, did not have a return. Thank you for helping me understand reduce better.
2

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);`

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.