skip to Main Content

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


  1. This simply uses a for loop to achieve your needed result. This might not be the best way to do it, though.

    const totalValue = 350
    const array = [70,180,70,70]
    
    function calcSumAndState(total, arr) {
        var sum = 0,i = 0
      for (i = 0; i<arr.length; i++) {
        sum+=arr[i]
        if (sum > total) {
            break;
        }
      }
      return {
        sum:sum,
        state:i
      }
    }
    var s = calcSumAndState(totalValue, array)
    console.log(s.sum)
    console.log(s.state)
    Login or Signup to reply.
  2. 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

    const maximum = 350;
    const array = [ 70, 180, 70, 70 ];
    
    let i = 0;
    let sum = 0;
    while (array[i] && (sum + array[i]) < maximum) {
        sum += array[i];
      i++;
    }
    console.log("sum",sum)

    .

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