Criteria to sort numbers as strings

Viewed 156

I know that a similar question exists here Javascript string conversion and array sort , but I need help in my version of the solution.

Task: The weight of a number is the sum of its digits. For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights in normal order can you give back this string ordered by "weights" of these numbers?

Example: "56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99" of FFC members When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since having the same "weight" (9) it comes before as a string.

Question: The only part I'm missing is how to do the last part so for example 180 will come before 207 and 90, similarly 207 before 45 and so on.

var arr = [56, 65, 74, 100, 99, 207, 45, 68, 86, 180, 90];
arr.sort(function(a, b) {
  var A = ("" + a).split("").reduce(function(c, d) {
    return Number(c) + Number(d);
  });
  var B = ("" + b).split("").reduce(function(e, f) {
    return Number(e) + Number(f);
  });
  if (A > B) {
    return A - B;
  } else if (A == B) {

    //I ASSUME I SHOULD WRITE SOMETHING HERE

  }
});

console.log(arr);

3 Answers
Related