Multiply each element of an array with Javascript

In this example we will multiply each element of an array with a value to demonstrate the use of the ECMAScript 6 Reflect.apply method.

First, lets create the function where the multiplication process will be done.

function multiplication(a) {
	let mutiply_array = [];
	this.value.forEach(function(element) {
		 mutiply_array.push(a * element);
	return mutiply_array;

Next we will use the Reflect.apply method to call the above multiplication function and multiply each element within an array specifies in the second parameter and with the value within the array specifies in the third parameter of the Reflect.apply method.

let multiply_apply = Reflect.apply(multiplication, {value:[1,2,3,4,5]}, [3]); // multiply element by 3

console.log( multiply_apply );

The outcome is a brand new array returns by the Reflect.apply method.

[ 3, 6, 9, 12, 15 ]

As you can see all the elements within the old array has been multiplied by 3!

Leave a Reply

Be the First to Comment!

Notify of