Home  >  Q&A  >  body text

How to find the sum of a set of numbers

<p>Given an array <code>[1, 2, 3, 4]</code>, how to find the sum of its elements? (In this example, the sum would be <code>10</code>.) </p> <p>I think <code>$.each</code> might work, but I'm not sure how to implement it. </p>
P粉642920522P粉642920522395 days ago424

reply all(2)I'll reply

  • P粉681400307

    P粉6814003072023-08-24 10:12:44

    That's exactly what does to reduce .

    If you are using ECMAScript 2015 (aka ECMAScript 6):

    const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
    console.log(sum); // 6

    For older JS:

    const sum = [1, 2, 3].reduce(add, 0); // with initial value to avoid when the array is empty
    
    function add(accumulator, a) {
      return accumulator + a;
    }
    
    console.log(sum); // 6

    Isn’t this beautiful? :-)

    reply
    0
  • P粉952365143

    P粉9523651432023-08-24 09:15:31

    Recommended (reduce by default)

    Array.prototype.reduce Can be used to iterate over an array, adding the current element value to the sum of previous element values.

    console.log(
      [1, 2, 3, 4].reduce((a, b) => a + b, 0)
    )
    console.log(
      [].reduce((a, b) => a + b, 0)
    )

    reply
    0
  • Cancelreply