Javascript - Counting array elements by reduce method until specific value occurs doesn't give a correct output

后端 未结 4 1676
陌清茗
陌清茗 2021-01-29 01:34
const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total)=>(num==0 ? total : total+num), 0) 
console.log(sum(arr, 0))

Please check how

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 01:54

    Since you need to stop summing values part way through the array, this might be most simply implemented using a for loop:

    const arr = [5, 6, 0, 7, 8];
    const num = 0;
    
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] == num) break;
      sum += arr[i];
    }
    console.log(sum);

    If you want to use reduce, you need to keep a flag that says whether you have seen the num value so you can stop adding values from the array:

    const arr = [5, 6, 0, 7, 8];
    
    const sum = (arr, num) => {
      let seen = false;
      return arr.reduce((c, v) => {
        if (seen || v == num) {
          seen = true;
          return c;
        }
        return c + v;
      }, 0);
    }
    
    console.log(sum(arr, 0));
    console.log(sum(arr, 8));

提交回复
热议问题