Search code examples
javascriptnumbers

how to convert an array element [ - 0 ] to a string?


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" ]


Solution

  • 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]))