Javascript sum raqamlari ketma-ketlikdagi har ikki raqamli ketma-ketlik bilan

Men bu mashq bilan yopiq bo'ldim, oxir-oqibat, sizga nima bo'ldi, deb aytaman, ammo mashq ta'rifidan oldin oldindan rahmat!

DESCRIPTION:

Raqamlar va harflar bilan bir qatorni oladi va uning raqamlari bilan bezatilgan qaytaradi. Harflar o'zgarishsiz qolmoqda Go'zallashtirish jarayoni barcha raqamlarni birlashtirib, raqamni bitta raqamli songa kamaytirishdir:

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

Mening kodim:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-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'])
</div> </div>

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

Bu summani amalga oshirishdan avval "oldingi" qadammi yoki men noto'g'ri narsa qilyapmanmi?

0
... dr (0) == 0 dan tashqari, 9 emas
qo'shib qo'ydi muallif georg, manba
raqamni obodonlashtirish uchun, algo = 9% bo'lsa (9% = 9%) bo'lsa, bo'lsa, oxirgi javob bo'ladi
qo'shib qo'ydi muallif sinsuren, manba

7 javoblar

Salom, siz sharhlarimda aytib o'tilganidek, bu kabi harakat qilib ko'rishingiz mumkin.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

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']))
</div> </div>

Tahrirlash: Taklif uchun rahmat @ kejor.

7
qo'shib qo'ydi
Salom @sinsuren Men sizning "if (sNumber% 9 == 0) newArray.push (9) ni tushunmayapman"; Agar array argumentlarini o'zgartirsam, ishlaysizmi?
qo'shib qo'ydi muallif Defoe, manba
@Defoe har qanday raqam uchun ishlaydi.
qo'shib qo'ydi muallif sinsuren, manba

Kodingizda o'zgartirishlar qildim. Iltimos, kerak bo'ladigan natijaga qarab kodni quyida toping.

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'])
3
qo'shib qo'ydi
18 ga nima javob beradi?
qo'shib qo'ydi muallif sinsuren, manba
Sizning kodingizda, har bir ajratilgan raqamni newArray-da qo'shyapsiz. Sizning natijangizga murojaat qilishingiz mumkin. Men barcha belgilar va 9 foizdan keyin ro'yxatga qo'shildim. Shunday qilib, Sizga kerak bo'lgan yagona raqamni qaytaradi.
qo'shib qo'ydi muallif Anavar Bharmal, manba
Ha, javobingizdan o'zgarishlar kiritdim. Rahmat.
qo'shib qo'ydi muallif Anavar Bharmal, manba

You can use Recursion + array.reduce

Recursion

<div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden">

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))
})
</div> </div>
2
qo'shib qo'ydi
Zo'r Rajesh! har bir odamning va men o'z ichiga olgan har bir satr nima qilayotganini tushunishi uchun ba'zi izohlar bera olasizmi?
qo'shib qo'ydi muallif Defoe, manba
Rahmat! @Rajesh!
qo'shib qo'ydi muallif Defoe, manba
@Defoe Men parchani yangilab oldim. Umid qilamanki yordam beradi
qo'shib qo'ydi muallif Rajesh, manba

Buni ko'ring:

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'])
1
qo'shib qo'ydi

Hech qanday mag'lubiyatsiz operatsiyalarsiz, bu mening halim bo'ladi;

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

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));
</div> </div>
0
qo'shib qo'ydi

Sizning namunangizda quyidagi qismni o'zgartirishingiz kerak:

:

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

ga:

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

newArray.push(mySum);
console.log(newArray);
0
qo'shib qo'ydi
Sizning oxirgi kodingiz rekursiya qaytib keladi: beautifyNumbers ([23,59, 4, 'A', 'b']) => [3, 9, 0, "A", "b" 4, 'A', 'b')
qo'shib qo'ydi muallif Defoe, manba
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;
 });
}
0
qo'shib qo'ydi
Javascript UZB
Javascript UZB
99 ishtirokchilar

@js_uzb @vuejs_uz @react_uz @nodejs_uz @angular_uz @ngTashkent @yiiframework_uz @laravel_uz @linux_uzbek @python_uz @swift_uzb —————— @uzdevgroup @UzGeeksGroup ——— @UzDev_Jobs @jobs_uzb