Multiply all elements in array

前端 未结 7 459
不思量自难忘°
不思量自难忘° 2020-12-05 10:16

I couldn\'t find an example here what I\'m really looking for. I\'d like to multiply all array elements, so if an array contains [1,2,3] the sum would be 1*2*3=6; So far I\'

相关标签:
7条回答
  • 2020-12-05 10:30

    The reduce() method executes a provided function for each value of the array and reduces the array to a single value

        const arr = [1,2,3];
        const sum = arr.reduce((prevValue,curValue) => {
            return prevValue * curValue
        },1);
        console.log(sum);

    prevValue is the initial value and it's equal 1 in this example

    curValue is the value of the current element in array

    0 讨论(0)
  • 2020-12-05 10:31

    If you want to multiply some consecutive numbers like 1,2,3 then, then apply this code and enter the number in the console (arr)

    let array = [];
    
    function factorisation(arr) {
        for (let j = arr; j > 0; j--) {
            array.push(j);
        }
        return multiply();
    }
    
    function multiply() {
        var sum = 1;
        for (var i = 0; i < array.length; i++) {
            sum = sum * array[i];
        }
        return sum;
    }
    
    console.log(factorisation(5));
    //5*4*3*2*1 = 120
    
    0 讨论(0)
  • 2020-12-05 10:34

    The cause is already known. Here's an alternative - using Array.reduce for your method:

    console.log( [1, 2, 3].reduce( (a, b) => a * b ) );
    console.log( Array.from( {length: 20} )
      .map( (v, i) => i + 1 )
      .reduce( (a,b) => a * b )
      .toLocaleString());
    
    // for empty arrays, use some initial value
    const arr = [];
    if (arr.reduce( (a, b) => a * b, -1 ) === -1) {
      console.error(`The given array ${arr} is empty`);
    }

    See also

    0 讨论(0)
  • 2020-12-05 10:37

    You need to have () when you call the function.

    Like multiply([1,2,3])

    Demo here

    0 讨论(0)
  • 2020-12-05 10:43

    You're not calling multiply as a function:

    multiply([1,2,3]);
    
    0 讨论(0)
  • 2020-12-05 10:45

    The alternative way to use Array.reduce should have the initial value set to 1 or else our function will return 0 no matter what.

    [1, 2, 3].reduce((a, b)=> a*b, 1)
    

    per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

    0 讨论(0)
提交回复
热议问题