Reputation: 133
I'm creating a function in angular and I want to reduce a list of objects like this example :
var tab =[{name:'i', value:13}, {name:'j', value:10},{name:'i', value:8}]
I want to get this result :
tab = [{name:'i', value:21},{name:'j', value:10}]
Upvotes: 0
Views: 301
Reputation: 691
If you are just chopping off the last element within an array you should be able to just use the reduceRight() function. Click here for more on the reduce Method
let tab =[{name:'i', value:13}, {name:'j', value:10},{name:'k', value:8}]
tab.reduceRight();
console.log(tab);
Upvotes: 1
Reputation: 31990
You can check whether the array contains an object with the same name
property with Array.find
, and if so, increment the value
property. Otherwise, push to the array.
var tab = [{name: 'i', value: 13}, {name: 'j', value: 10}, {name: 'i', value: 8}]
const result = tab.reduce((a, b) => {
let found = a.find(e => e.name == b.name);
return found ? found.value += b.value : a.push(b), a
}, [])
console.log(result);
Upvotes: 2
Reputation: 1334
The answer provided by Spectric is a default solution for this problem and would be preferred in most cases as it is clear and straightforward. However I asked myself if we can solve it without additional iteration (via find
function) and came up with following solution.
var tab = [{ name: 'i', value: 13 }, { name: 'j', value: 10 }, { name: 'i', value: 8 }, { name: 'j', value: 8 }];
const result = tab.reduce((a, b, i) => {
let found = a.tmp.hasOwnProperty(b.name);
return !found ? a.res[a.tmp[b.name] = i] = b : a.res[a.tmp[b.name]].value += b.value, a;
}, { tmp: {}, res: [] }).res;
console.log(result);
It is adding auxiliary tmp object saving index of a given unique element in the result array and allows us to do everything in one iteration. I could imagine this to be better in terms of performance if we had a lot of objects of only few distinct types.
Upvotes: 1