Home > Net >  How to sum numbers in array by index in javascript
How to sum numbers in array by index in javascript

Time:06-03

I have an array

const array = [6,2,6,7,5,9];

I want sum of all numbers till 7 in array

I tried .reduce but it gave me sum of whole array, How can I do that so?

CodePudding user response:

You're going to have to jump through a lot of hoops with reduce. You'd need to find the index of 7, then splice up to that index, and then reduce over the spliced array. Muy complicado!

It's much simpler to create a sum variable, and loop over the array. Add each number to the sum, and when the number is 7 break the loop.

It's worth noting this strategy wouldn't work for duplicate numbers like 6 for example because which 6 would you choose?

const arr = [6, 2, 6, 7, 5, 9];

let sum = 0;

for (const n of arr) {
  sum  = n;
  if (n === 7) break;
}

console.log(sum);

CodePudding user response:

This is doable with just a for loop:

const array = [6, 2, 6, 7, 5, 9];
let sum = 0;

for (let i = 0; i < array.length; i  ) {
  sum  = array[i];
  if (array[i] == 7) break;
}

// outputs the sum of [6,2,6,7], which is 21
console.log(sum);

Here we take the sum of numbers till 7 to mean the sum of all numbers in our array up until the first instance of 7.

CodePudding user response:

Here you go,

const array = [6, 2, 6, 7, 5, 9];
const found = array.find(element => element >= 7);
const newArr = array.indexOf(found);
const arr1 = array.slice(0,(newArr   1));
const sum = 0;
const result = arr1.reduce(
  (previousValue, currentValue) => previousValue   currentValue,
  sum
);

console.log(result); //output 21

CodePudding user response:

Try using this. This is going to loop trow and store the sum until it's 7.

const array = [6, 2, 6, 7, 5, 9]
let sum = 0

array.forEach((number) => {
  if (sum <= 7) sum  = number
})

console.log(sum) // Output: 8

CodePudding user response:

Do write the following code before you reduce it!

const arr1 = array.slice(0,4);

and then reduce arr1. you will get your desired Answer! oh and please change the name of the constant however you want!

  • Related