Aaron Janse Aaron Janse - 1 year ago 99
Javascript Question

How to negate all elements in javascript array

What is the shortest way to negate all elements in a javascript array, with reasonable efficiency?

For example, the solution would convert

[0, 18, -1, -2, 1, 3]
[0, -18, 1, 2, -1, -3]

The solution does not need to handle any values that are NaN/undefined/null, because the array I need this for does not contain any of those values.

Here is what I normally do (with array

for(var i = 0; i < array.length; i++) {

The problem is that I need to invert this array in several places, so don't want to reuse large code.


Answer Source

That would be array.map returning the negative of each value. Adding in arrow function for an even shorter syntax.

var negatedArray = array.map(value => -value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download