How do I multiply an array within a function in JS?

Asked

Viewed 9,010 times

-3

The question is basically this: We need a product function that takes an array of numbers and returns the product: the result of multiplying all the elements among themselves.

For example, product([1, 4, 7]) should return 28, which is 1 * 4 * 7.

5 answers

6

You can use the rest operator for that reason:

function mult(...terms) {
  let current = 1
  for (const term of terms) current *= term
  
  return current
}

console.log(mult(1, 4, 7))

If you want to use one array in the first parameter, simply swap ...terms for terms:

function mult(terms) {
  let current = 1
  for (const term of terms) current *= term
      
  return current
}

console.log(mult([1, 4, 7]))

5

The array has a function reduce that returns a single value according to the existing elements.

reduce

The method reduce() performs a function reducer (provided by you) for each member of the array, resulting in a single return value.

Example:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Applying to your problem:

const multiplicar = (itens) => itens.reduce((acumulador, item) => acumulador * item);

console.log(multiplicar([1, 4, 7]));

2

You can use the for classic which is also compatible with Internet Explorer 11:

function produto(v){
   var res = 1;
   for(var x = 0; x < v.length; x++) res *= v[x];
   return res;
}

console.log(produto([1, 4, 7]));

  • 1

    because you used "var res = 1", not "0" ?

  • It begins in 1 because 1 is the neutral term of multiplication, also called the neutral element or identity element. See more in https://pt.wikipedia.org/wiki/Elemento_neutro

  • 1

    If starting with zero, the multiplication result will always be zero, regardless of the numbers in the array

1

I think that will solve the case:

var result = [1, 4, 7].reduce( (a,b) => a * b );

-2

PROBLEM:

We need a product function that takes an array of numbers and returns the product: the result of multiplying all the elements among themselves.

For example, product([1, 4, 7]) should return 28, which is 1 * 4 * 7.


SOLUTION:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.