skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search