Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] to [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 array):

for(var i = 0; i < array.length; i++) {
  array[i]*=-1
}

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

Thanks

like image 662
user31415 Avatar asked Sep 24 '26 01:09

user31415


2 Answers

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);
like image 111
Joseph Avatar answered Sep 26 '26 13:09

Joseph


negate all elements in a javascript array

I think you are referring to negate only the positive number.

var _myArray = [0, 18, -1, -2, 1, 3]
var _invArray = [];
_myArray.forEach(function(item){
  item >0 ?(_invArray.push(item*(-1))) :(_invArray.push(item))
})
console.log(_invArray);

JSFIDDLE

like image 24
brk Avatar answered Sep 26 '26 14:09

brk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!