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?
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);
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.
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