3

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

user31415
  • 446
  • 7
  • 16
  • 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 Jul 05 '16 at 02:26

2 Answers2

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);
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 3
    Nice approach though it gives `-0`. – choz Jul 05 '16 at 02:24
  • Is -0 any different than 0? – user31415 Jul 05 '16 at 02:25
  • 1
    isn't this even simpler `array.map(value => -value);` since, as @AaronJanse points out, he doesn't need to handle nulls or undefineds – mr rogers Jul 05 '16 at 02:28
  • 1
    @choz `-0` is different than `+0`. Otherwise, `1/+0` and `1/-0` would also be the same. – Oriol Jul 05 '16 at 02:33
  • @Oriol Both result in Infinity, even though their binary representation are not same. – choz Jul 05 '16 at 02:39
  • 1
    @choz No, `1/+0` is `+Infinity`, and `1/-0` is `-Infinity`. And clearly `+Infinity !== -Infinity`, e.g. `-Infinity < +Infinity`. You can also test `Object.is(+0, -0)`, which produces `false` (they are different). – Oriol Jul 05 '16 at 02:41
  • 2
    @Oriol Let's not go to deep.. `+0 === -0` alright.. This [article](http://stackoverflow.com/questions/7223359/are-0-and-0-the-same) might help. – choz Jul 05 '16 at 02:42
  • There are some features that are bad just because they aren't obvious and cause "bugs" due to user error. One of which is the difference between +0 and -0 – user31415 Jul 05 '16 at 02:52
  • From now on, I will use this for tons of things, not just negating. – user31415 Jul 05 '16 at 16:22
  • I have used it like this: `var negatedArray = myArray.map(value => value !== 0 ? -value: value );` To avoid confusion of +/- 0 – HardikDG Jun 25 '17 at 08:49
1

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

brk
  • 48,835
  • 10
  • 56
  • 78
  • No, but good solution. `_invArray.push(-Math.abs(item))` could have worked too, if that was what I was looking for – user31415 Jul 05 '16 at 16:22