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;
2
Answers
You can simply get an index from user by using the below code:
let indexNumber = prompt("Provide index number")
Then, place the indexNumber in for loop. Assign this variable to i = indexNumber instead of i = 0.Then write for loop syntax and then add the conditional basd value in another variable and return it
You can achieve the required result in the following way:
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:And, as @DM suggested, I am now avoiding the
slice()
call and replacing it with a test on the inner indexi
.