简体   繁体   中英

how to get index of element in array after a sum equals some number of previous elements

Sum of elements const sum = 4;

I want to check all the elements from zero index and sum until elements sum equals 4 and get the immediate index (next index where the sum ends with an element)

for eg a sample of array's::

const sampleArr1 = [1,2,1,4,...]

here the exp o/p is index of 4 which is 3

const sampleArr2 = [1,3,7,...]

here the exp o/p is index of 7 which is 2

const sampleArr3 = [4,10,...]

here the exp o/p is index of 10 which is 1

I have got no clue on how could I do this, any help is appreciated

let sum = 0;
let immediateIndex = 0;
for (let i = 0; i < array.length; i++) {
    sum += array[i];
    if(sum === 4) {
        immediateIndex = i + 1;
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM