Question #347240

Product of array Items

given an array integers,write JS program to get the product of the integers in the given array.

input

the input will be containing single line integers.

output

the output should be single line containing the product as shown in sample outputs.


input1

[1,2,3]

output1

[1 * 2 * 3 = 6]

input2

[-1, -2, -3]

output2

[-1*-2*-3 = -6]


Note: The Output should be displayed as [1 * 2 * 3 = 6]



Expert's answer

The example below is the shortest way to achieve your goal.


Use Array.prototype.reduce to multiply integers (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).


Use Array.prototype.join to concatenate all elemenets in an array using some delimeter (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join).



function giveMeAProductOfArrayItems(input) {
	if (input.length !== 0) {
    var multiply = input.reduce(function(prevValue, currValue) {
  	  return prevValue * currValue;
  	}, 1);
  	
  	return "[" + input.join(" * ") + " = " + multiply + "]";
  } else {
    return "[]";
  }
}

console.log(giveMeAProductOfArrayItems([]));
console.log(giveMeAProductOfArrayItems([1,2,3]));
console.log(giveMeAProductOfArrayItems([-1,-2,-3]));
LATEST TUTORIALS
APPROVED BY CLIENTS