I’m using ReactJS and I want to do some check and update state
Example : I have an array like this : const array=[70, 180, 70, 70] and another value const totalValue=350
I want to map on the array and add each element to the previous one, and when the amount is greather than totalValue I should stop and update state.
for Example : 70 + 180 = 250 so I should continue
70+80+70 = 320 I should continue
70+ 180+ 70+ 70 = 390 ;
So I should stop and update my state to 3 (3 is the length of the array when I’ve stopped)
I’ve tried a map and some array[index] but it’s hard to understand..
This is what I’ve tried :
[ 70, 180, 70, 70 ].map((el,index,array) => {
return el + array[index]
})
Sorry for my english
[ 70, 180, 70, 70 ].map((el,index,array) => { return el + array[index] })
2
Answers
This simply uses a for loop to achieve your needed result. This might not be the best way to do it, though.
A while loop may be a good solution. Keep a running a total and check that the sum + the next value isn’t more than the maximum you’ve defined
.