44

For example, how do I achieve the following without iterating over the array?

var a = [1, 2, 3] * 5;  // a should equal [5, 10, 15]
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
stephjang
  • 939
  • 1
  • 8
  • 13
  • 3
    You will always be iterating over the array, but if you don't want to do it explicitly you always have `map` on the array object. It is not compatible with all browsers though. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map – bennedich Dec 10 '11 at 07:02
  • 1
    You could use underscore.js - it has a map function that would do this for you :) else you have to loop over it somehow even if you were to code the implementation yourself – PhD Dec 10 '11 at 07:04
  • 1
    Scalar: A single number (used when dealing with vectors or matrices) – nCardot Nov 04 '21 at 06:11

10 Answers10

46

Array.map() is available to IE users as of IE9, so if you don't care about compatibility at all you can use this:

var a = [1, 2, 3].map(function(x) { return x * 5; });

For JavaScript 1.8, this is as short as you can go:

var a = [1, 2, 3].map(function(x) x * 5);

If you need maximal browser compatibility, you'll have to put up with a loop.

Either way you'll be iterating over the array; Array.map() just makes it less obvious you're doing so.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 1
    Thanks for explaining the browser compatibility tradeoff. – stephjang Dec 10 '11 at 07:51
  • 3
    Note that JavaScript 1.8's syntax is non-standard and unlikely to be implemented by anyone apart from Mozilla. Harmony will likely included some lambda syntax, though it is as-of-yet undecided what (those JS 1.8's is already out of the running). – gsnedders Dec 10 '11 at 14:28
  • Also note that you've got an extra array allocation with `.map` –  Jun 25 '15 at 10:51
  • 7
    ES6 - `var a = [1, 2, 3].map(x => x * 5)` – Dhiraj Barnwal Aug 06 '18 at 15:38
37

In ECMAScript 6, you can use arrow functions:

var a = [1, 2, 3];
var b = a.map(x => x * 5); // <-------

console.log(b);   // [5, 10, 15]

Arrow functions are syntactic sugar for an inline function with lexical this binding:

// ES6
let array2 = array1.map(x => x * 5);
// ES5
var array2 = array1.map((function (x) { return x * 5; }).bind(this));

Therefore, if you need to support Internet Explorer or other old browsers (Edge understands ES6) you can use babeljs or TypeScript in your project to cross-compile your code to ES5 syntax.

Leon Adler
  • 2,993
  • 1
  • 29
  • 42
17
for(var i=0; i<a.length; i++) {
    a[i] *= 5;
}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • 1
    Ugh, so this is the only way? Nasty. – stephjang Dec 10 '11 at 06:56
  • 1
    @stchangg: For compatibility, yeah. – BoltClock Dec 10 '11 at 06:57
  • 2
    @stchangg - why is this nasty? This is programming :) – PhD Dec 10 '11 at 07:05
  • `for (i in array)` should not be used with arrays because it includes properties of the object in its iteration that are not actually items in the array - it is meant for iterating properties, not just array elements. It will work in some cases, but is asking for trouble. – jfriend00 Dec 10 '11 at 07:37
  • 2
    @Nupul I guess because I'm used to more array support after using MATLAB. =/ Although it seems that other languages like Python and Ruby don't have this functionality out of the box either, their iteration syntax is more concise. Also, Javascript just seems to have less built-in functionality. I mean, it's kind of surprising that [Javascript doesn't come with a string interpolation function by default](http://stackoverflow.com/questions/1408289/best-way-to-do-variable-interpolation-in-javascript). – stephjang Dec 10 '11 at 07:48
  • @stchangg - for really nasty do it in one line: `for (var i=0; i < a.length; a[i++]*=5);` – nnnnnn Dec 10 '11 at 10:14
5

Ecmascript 2016 (ES7) defines SIMD mathematics which allow to do multiplications like the one you desire faster and easier. However, as of today there is very little browser support for SIMD (only Firefox nightly builds support this) [1], [2]. This is how it will look like:

var a = SIMD.Float32x4(1, 2, 3);
var b = SIMD.Float32x4(5, 5, 5);
SIMD.Float32x4.mul(a, b);  // Float32x4[5, 10, 15]

Until there will be widespread support for SIMD you'd have to resort to using map

var a = [1, 2, 3].map(function(x) { return x * 5; });

which is nicely supported by all modern browsers [3].

  • For everyone coming here from Google in "the future", SIMD was removed from the ES2016 standard and work on it is done in WebAssembly instead. No modern browser supports this in plain JavaScript. – Leon Adler Mar 12 '23 at 12:10
3

As stated in Docs:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

In my opinion, .map() is more suitable if someone wants to create a new array based on input values from the current array.

However, if someone wants to modify the array in place, .forEach() seems a better choice.

In ES6 we may use:

Following code will modify a given array arr in place (without creating a new one):

arr.forEach((value, index) => {arr[index] *= 5});

Demo:

var arr = [1, 2, 3];
var scalar = 5;

arr.forEach((value, index) => {
    arr[index] *= scalar;
});
console.log(arr);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
2

You can use .map but you also have to create a new variable to throw the new values in:

var a = [1,2,3];

var b = a.map(function(x){
    return x * 5;
});

alert(b);
Alvaro Gómez
  • 39
  • 1
  • 4
1
var a, i, ii, term;

a = [1,2,3];
term = 5;

for (i=0, ii=a.length; i<ii; i++) {
  a[i] = a[i] * term;
}
bennedich
  • 12,150
  • 6
  • 33
  • 41
1

You can try this:

function scalarMultiply(arr, multiplier) {
   for (var i = 0; i < arr.length; i++)
   {
      arr[i] *= multiplier;
   }
   return arr;
}

USAGE

var a = scalarMultiply([1, 2, 3], 5);
Abdul Munim
  • 18,869
  • 8
  • 52
  • 61
0

Using Lodash's map function, this returns the original array a, multiplied by the constant 5:

_.map(a, function multiply(x) { return x * 5; });
Dolan
  • 313
  • 1
  • 4
  • 14
scottlittle
  • 18,866
  • 8
  • 51
  • 70
0

I think it's not possible without iteration.

with iteration, here are the methods:

let a=[1,2,3,4] 

then,

method 1:

a=a.map(e=>{return e*5})

method 2:

a.forEach((e,i)=>a[i]=5*e)
aakash4dev
  • 774
  • 4
  • 13