Answer to Question #347240 in HTML/JavaScript Web Application for ram

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]



1
Expert's answer
2022-06-01T12:54:14-0400

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]));

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS