admin管理员组

文章数量:1336633

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

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

Share edited Jul 5, 2016 at 2:38 user31415 asked Jul 5, 2016 at 2:21 user31415user31415 4667 silver badges16 bronze badges 1
  • 2 What did you try? Shouldn't have been difficult to at least make an attempt and show that attempt rather than ask how to do it from scratch – charlietfl Commented Jul 5, 2016 at 2:26
Add a ment  | 

2 Answers 2

Reset to default 6

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);

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

本文标签: How to negate all elements in javascript arrayStack Overflow