0

I am trying to convert an array of numbers to an array of strings and get the first character in each element of the array. Tell me what I am doing wrong that I get "0" and not "-" in the last element?

function example

function invert(array) {

  let q = array.map(i => i.toString()[0])
}
invert([-10,8,-2,-0])

result Array(4) [ "-", "8", "-", "0" ]

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Ivan M
  • 3
  • 1
  • 3
    Simply because `(-0).toString()` is `"0"`? String conversion ignores the peculiarity that negative zero is and handles any zero as 0. – Bergi Jan 30 '23 at 20:05
  • `(-0).toLocaleString()` appears to be `"-0"`. – Sebastian Simon Jan 30 '23 at 20:17
  • @SebastianSimon: Of course, you'd need to verify it will behave that way in all locales (I don't know of any guarantees there), and/or be okay with the formatting differing by locale. – ShadowRanger Jan 30 '23 at 20:19

2 Answers2

3

Per MDN's Number.toString docs:

Both 0 and -0 have "0" as their string representation.

If you want it to have a negative sign, you'll have to special case -0 (this can be harder than it seems).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
2

Based on this answer Are +0 and -0 the same? you can use Object.is to check if a number is -0

function invert(array) {
  return array.map(i => Object.is(i, -0) ? '-' : i.toString()[0])
}
console.log(invert([-10,8,-2,-0]))
Konrad
  • 21,590
  • 4
  • 28
  • 64