Square Every digit Kata

I attempted a Kata where every digit in a number was to be squared, so 56 would be 2536 and 9119 would be 811181 for example.  The way it looked to me to best tackle this problem was to use the toString method on numbers, create an array, using a loop put into the array the square of the digits in the number.  So my solution was as follows.

function squareDigits(num) {

         var numStr = num.toString();

         var sq = [];

         for(var i=0; i<numStr.length; i++) {

sq[i] = numStr[i] * numStr[i];


         return Number(sq.join());


This is a reasonable solution I thought it was good, however not one upvote.  The cleverest solution made use of split and map methods.  The split method splits a string into an array of substrings.  Whilst the map method which creates a new array with the results of calling a function for every array element. Also it calls the provided function once for each element in an array, in order.  If though an array element does not have a value, it is not executed.

So the clever and best practise solution could of course be one lined.

function squareDigits(num){

      return Number(( + num).split().map(function (val) { return val * val;}).join());



Leave a Reply

Your email address will not be published. Required fields are marked *