What is the best way to return the sum of an array from a certain index that matches a criteria.
For example, I want to find the sum of each array from index 1 with values less than or equal to 4;
a = [];
a[0] = {};
a[0].age = [3,4,8,12,1];
a[0].result = 0;
a[1] = {};
a[1].age = [5,1,3,2,10,12];
a[1].result = 0;
// Formula should return a[0].result = 5; a[1].result = 6;
I know I can loop over each array but wondered if there was a more suitable way as ultimately there will be a lot more arrays;
You can achieve the required result in the following way:
const a = [{age:[3,4,8,12,1],result:0},
{age:[5,1,3,2,10,12],result:0}];
a.forEach(e=>e.result=e.age.slice(1).reduce((sum,c)=>sum+(c<=4?c:0),0));
console.log(a);
As an initialised result
property does already exist in each object (with the value 0) you could even substitute the .reduce()
by a simpler .forEach()
call:
const a = [{age:[3,4,8,12,1],result:0},
{age:[5,1,3,2,10,12],result:0}];
a.forEach(e=>e.age.forEach((c,i)=>{if(i&&c<=4)e.result+=c}));
console.log(a);
And, as @DM suggested, I am now avoiding the slice()
call and replacing it with a test on the inner index i
.