Multiply a number to an array
javascript
Solution
You can indeed use the `map` function:
function multiply(input) {
return input * 3;
}
var myArray = [1, 2];
var myNewArray = myArray.map(multiply);
What this does is perform a function you provide on each element in the array, and return a new array with the results.
If you're already using jQuery, you can make it a little more concise with the `each` function:
$.each(myArray, function(index, value) {
myArray[index] = value * 3;
});
This changes the existing array. Although, using the plain-JS approach, you could do `myArray = myArray.map(multiply);` if you don't want a new variable.
I made a jsFiddle as an example.
Problem
From the following thread (Multiplying an array with a single value by a number?) I got the information that it is not possible to multiply a number to all elements within an array by executing `[1, 2]*3`. But since I have to do this I was wondering if there is an smart way of doing this? I know I could write a function which iterates through all elements and multiply a number to each element manually. But I was wondering if there is a smarter way out there? Maybe there are some libraries out there which implements some math functions where I can multiply a number to all elements of an array? Or do you think the map function of Array can be used for this purpose?