Languages

JavaScript - multiply each item of array by scalar?

0 points
Asked by:
Aran-Busby
592

How can I multiply each item of an array by a scalar in JavaScript?

I need something like:

var array = [1, 2, 3] * 10;

To get array consisting of:

[10, 20, 30]
1 answer
0 points
Answered by:
Aran-Busby
592

You can use map() method to do this.

Practical examples

ES6+ solution:

// ONLINE-RUNNER:browser;

const array = [1, 2, 3];

const result = array.map((x) => x * 10);

console.log(result); // [ 10, 20, 30 ]

For older versions of JavaScript:

// ONLINE-RUNNER:browser;

var array = [1, 2, 3];

var result = array.map(function (x) {
    return x * 10;
});

console.log(result); // [ 10, 20, 30 ]

 

References

  1. Array.prototype.map() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join