My code fails the tests, what am I doing wrong? at the same time help improve the code itself?

function digitize(n) { var str = String(n); var str1 = str.split('').reverse(); return str1; } digitize(35231); 

You need to get: '[1, 3, 2, 5, 3]', instead I get: '[\' 1 \ ', \' 3 \ ', \' 2 \ ', \' 5 \ ', \' 3 \ ']

  • but your code doesn't sort the array - Grundy
  • @Grundy and I thought sorts r str1 = str.split('').reverse(); why not, do not tell me? - anonim
  • because when sorting you would have: 1,2,3,3,5 - Grundy
  • but after all I meant by sorting, much wider shorter, not only in the context of js / therefore I could confuse you. It was easier to say, say, to return the array, with the reverse order of the elements. - anonim
  • here sorting in any form would sort , and here you just expanded the array. - Grundy

5 answers 5

It is necessary to make a cast:

 var arr = digitize(35231); console.log(arr); function digitize(n) { n = String(n).split('').reverse().map(Number); return n; } 

Source: map , the global Number object.

    You need to convert all characters to int Here is the working version:

     function digitize(n) { var str = String(n); var str1 = str.split('').reverse(); for(var i=0; i<str1.length;i++) str1[i] = parseInt(str1[i], 10); return str1; } digitize(35231); 

      As an alternative to reverse , map, you can use the reduceRight method .

       function digitize(n) { return [].reduceRight.call(String(n), (acc, char) => acc.concat(+char), []); } console.log(digitize(35231)); 

        You can do this

         var arr = digitize(35231); console.log(arr); function digitize(n) { n = String(n).split('').reverse().join(); return n; } 

        • judging by the question - the return value should be an array of numbers, not a string - Grundy
        • @Grundy judging by the intended answer - just the line: You must get: '[1, 3, 2, 5, 3]' - Trymount
        • but even in this case, the example displays something completely different: 1,3,2,5,3 instead of '[1, 3, 2, 5, 3]' - Grundy
        • @Grundy here yes, cant. But no one provided input data) - Trymount
        • one
          The input is: this is a number. But with the weekend there really is a slight misunderstanding. But judging by the question of converting a number into a back-sorted array , you need an array, not something else - Grundy
         function digitize(n){ return (n + '').split('').map(Number).reverse(); } 
        • What is it more modern? - Grundy
        • agree nothing. but better than the original version so post it - anonim
        • and the better the original version? - Grundy
        • Be polite. Expressions like the ones you give are unacceptable on Stack Overflow. Please add a comment to the code you provided. In its current form, with high probability, it will be incomprehensible to colleagues who came to the question from the search engine. - Nicolas Chabanovsky