最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript sum numbers in an array by two digit sequence each - Stack Overflow

programmeradmin4浏览0评论

I'm stuck with this exercise, at the end I tell you what is my output but before the description of the exercise, thanks in advance!

DESCRIPTION:

It receives an array with numbers and letters and returns it with its numbers beautified. Letters remain unchanged Beautify process is to reduce a number into a single digit number by adding all its digits together:

123 = 6 because 1+2+3 = 6
9 = 9
9956 = 2 because 9+9+5+6 = 29 -> 2+9 = 11 -> 1+1 = 2
793 = 1 because 7+9+3 = 19 -> 1+9 = 10 -> 1+0 = 1
Example: beautifyNumbers([23,59, 4,'A','b']) returns [5, 5, 4, 'A', 'b']

my CODE:

function beautifyNumbers(array) {

  var newArray = [];
  array.forEach(function(element) {
    // Checks if character is a letter and not a number
    if (typeof element == "number") {
      var sNumber = element.toString();

      for (var i = 0, len = sNumber.length; i < len; i += 1) {
        newArray.push(+sNumber.charAt(i));
        // The "+" sign converts a String variable to a Number, if possible: +'21.2' equals Number(21.2).
        // If the conversion fails, it return NaN.
        // El método charAt() de String devuelve el carácter especificado de una cadena:
        // var name="Brave new world"; name.charAt(0) => 'B'
      }
      console.log(newArray);;
    } else {
      // pushes numbers to the array without making
      // any change to them
      newArray.push(element);
    }
  });
  // returns the array
  return newArray;


}

beautifyNumbers([23, 59, 4, 'A', 'b'])

I'm stuck with this exercise, at the end I tell you what is my output but before the description of the exercise, thanks in advance!

DESCRIPTION:

It receives an array with numbers and letters and returns it with its numbers beautified. Letters remain unchanged Beautify process is to reduce a number into a single digit number by adding all its digits together:

123 = 6 because 1+2+3 = 6
9 = 9
9956 = 2 because 9+9+5+6 = 29 -> 2+9 = 11 -> 1+1 = 2
793 = 1 because 7+9+3 = 19 -> 1+9 = 10 -> 1+0 = 1
Example: beautifyNumbers([23,59, 4,'A','b']) returns [5, 5, 4, 'A', 'b']

my CODE:

function beautifyNumbers(array) {

  var newArray = [];
  array.forEach(function(element) {
    // Checks if character is a letter and not a number
    if (typeof element == "number") {
      var sNumber = element.toString();

      for (var i = 0, len = sNumber.length; i < len; i += 1) {
        newArray.push(+sNumber.charAt(i));
        // The "+" sign converts a String variable to a Number, if possible: +'21.2' equals Number(21.2).
        // If the conversion fails, it return NaN.
        // El método charAt() de String devuelve el carácter especificado de una cadena:
        // var name="Brave new world"; name.charAt(0) => 'B'
      }
      console.log(newArray);;
    } else {
      // pushes numbers to the array without making
      // any change to them
      newArray.push(element);
    }
  });
  // returns the array
  return newArray;


}

beautifyNumbers([23, 59, 4, 'A', 'b'])

An the output I receive is => [2, 3, 5, 9, 4, "A", "b"]

Is this the "previous" step before doing the sum or am I doing something wrong?

Share Improve this question edited Oct 3, 2016 at 10:45 Rajesh 25k5 gold badges50 silver badges83 bronze badges asked Oct 3, 2016 at 10:43 DefoeDefoe 3711 gold badge5 silver badges19 bronze badges 2
  • 2 to beautify the number, the algo will be if (number % 9 == 0) then 9 else number%9 will be the final answer – sinsuren Commented Oct 3, 2016 at 10:47
  • 2 ...except that dr(0) == 0, not 9 – georg Commented Oct 3, 2016 at 11:21
Add a ment  | 

7 Answers 7

Reset to default 8

Hi you can try like this as mentioned by me in ments.

function beautifyNumbers(array) {
  var newArray = [];
  array.forEach(function(element) {
    // Checks if character is a letter and not a number
    if (typeof element == "number") {
      if(element %9 == 0 && element != 0)
        newArray.push(9);
      else 
        newArray.push(element%9);
    } else {
      newArray.push(element);
    }
  });
  return newArray;
}
console.log(beautifyNumbers([1231, 0, 18, 27, 12354, 59, 4, 'A', 'b']))

Edit: Thanks @georg for suggestion.

I have made changes in your code. Please find below code, which is giving result as per your need.

function beautifyNumbers(array) {
            var newArray = [];
            array.forEach(function (element) {
                // Checks if character is a letter and not a number
                if (typeof element == "number") {
                    var sNumber = element.toString();
                    var beutifySum = 0;
                    for (var i = 0, len = sNumber.length; i < len; i += 1) {
                        beutifySum += +sNumber.charAt(i);
                    }

                    beutifySum = beutifySum % 9 === 0 ? 9 : beutifySum % 9;
                    newArray.push(beutifySum);
                } else {
                    // pushes numbers to the array without making
                    // any change to them
                    newArray.push(element);
                }
            });

            console.log(newArray);
            // returns the array
            return newArray;
        }

beautifyNumbers([23, 59, 4, 'A', 'b'])

You can use recursion + array.reduce

Recursion

function sumOfDigits(num) {
  // Check if value is number or alphanumeric
  if (!isNaN(num)) {
    // Convert number and split to get individual values.
    // Loop over values and add them
    var sum = num.toString().split("").reduce(function(p, c) {
      // +p is a shorthand for parseInt(p)
      return +p + +c;
    });

    // check if number is greater than 10. If yes, repeat the process
    if (sum >= 10) sum = sumOfDigits(sum);
    return sum;
  } 
  // if value is not number, return value
  else return num;
}

var data = [123, 4, 567, 'a', "abc", 0];
data.forEach(function(n) {
  console.log(sumOfDigits(n))
})

Try like this:

function beautifyNumbers(array) {

  var newArray = [];
  array.forEach(function(element) {
    // Checks if character is a letter and not a number
    if (typeof element == "number") {
      newArray.push(beautifyElement(element));
    } else {
      // pushes numbers to the array without making
      // any change to them
      newArray.push(element);
    }
  });
  // returns the array
  return newArray;


}

   function beautifyElement(element){
    var sNumber = element.toString();
    var sum = 0;
    for (var i = 0, len = sNumber.length; i < len; i += 1) {
        sum = sum + +sNumber[i];
    }
    if(sum>9){
        return beautifyElement(sum);
    }else{
        return sum;
    }
}

beautifyNumbers([23, 59, 4, 'A', 'b'])
function bsum(v) {
    var res = (v+"").split('').reduce(function(a, b) {return (a | 0) + (b | 0);});
    if(res | 0 > 10) return bsum(res) ;
    else return res;
}

function beautifyNumbers(array) {
 return array.map(function(v, i) {
    if (typeof v == 'number') {
        return bsum(v) | 0;
    }
     else return v;
 });
}

In your example you should change the part with:

from:

for (var i = 0, len = sNumber.length; i < len; i += 1) {
    newArray.push(+sNumber.charAt(i));
}
console.log(newArray);;

to:

var mySum = 0;
for (var i = 0, len = sNumber.length; i < len; i += 1) {
    mySum += sNumber.charAt(i);
}

newArray.push(mySum);
console.log(newArray);

Pure functional without any string operations this would be my solution;

function funnySum(n){
  var d = Math.floor(Math.log10(n) +1),  // get number of digits
    sum = Array(d).fill()                // prepare the array and place digits
                  .map((_,i) => Math.floor(n % Math.pow(10,d-i) / Math.pow(10,d-1-i)))
                  .reduce((p,c) => p+c); // get sum of array items
  return sum > 9 ? funnySum(sum) : sum;  // if still two digits continue...
}

console.log(funnySum(9956));

发布评论

评论列表(0)

  1. 暂无评论