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?
Hi you can try like this as mentioned by me in comments.
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.