Sorting according to weights of numbers in JavaScript

In this problem, we need to sort an array of numbers according to their weights using JavaScript. The weight of a number is defined as the sum of its digits, and we'll create functions to calculate weights and perform the sorting.

Understanding the Problem

We have to sort numbers according to their weights, where a weight is the sum of a number's digits. For example, if we have an array [19, 11, 12, 15]:

  • Weight of 19 = 1 + 9 = 10
  • Weight of 11 = 1 + 1 = 2
  • Weight of 12 = 1 + 2 = 3
  • Weight of 15 = 1 + 5 = 6

After sorting by weights: [11, 12, 15, 19] (weights: 2, 3, 6, 10).

Algorithm

Step 1: Create a function to calculate the weight (sum of digits) of any number.

Step 2: Create a sorting function that uses the weight calculation to compare numbers.

Step 3: Use JavaScript's sort() method with a custom comparison function.

Step 4: Handle ties by comparing numerical values when weights are equal.

Implementation

// Calculate the weight (sum of digits) of a number
function getWeight(num) {
    let sum = 0;
    while (num > 0) {
        sum += num % 10;
        num = Math.floor(num / 10);
    }
    return sum;
}

// Sort numbers by their weights
function sortByWeight(nums) {
    return nums.sort((a, b) => {
        const weightA = getWeight(a);
        const weightB = getWeight(b);
        
        // If weights are equal, sort by numerical value
        if (weightA === weightB) {
            return a - b;
        }
        // Otherwise, sort by weight
        return weightA - weightB;
    });
}

// Example usage
const numbers = [123, 56, 12, 478, 99];
console.log("Original array:", numbers);
console.log("Sorted by weight:", sortByWeight([...numbers])); // Use spread to avoid mutating original

// Let's show the weights for clarity
numbers.forEach(num => {
    console.log(`Number ${num} has weight ${getWeight(num)}`);
});
Original array: [ 123, 56, 12, 478, 99 ]
Sorted by weight: [ 12, 123, 56, 99, 478 ]
Number 123 has weight 6
Number 56 has weight 11
Number 12 has weight 3
Number 478 has weight 19
Number 99 has weight 18

Alternative Implementation Using String Method

// Alternative way to calculate weight using string conversion
function getWeightString(num) {
    return num.toString()
              .split('')
              .reduce((sum, digit) => sum + parseInt(digit), 0);
}

// Example with both methods
const testNumbers = [45, 123, 7, 89];
testNumbers.forEach(num => {
    console.log(`Number ${num}: Math method = ${getWeight(num)}, String method = ${getWeightString(num)}`);
});
Number 45: Math method = 9, String method = 9
Number 123: Math method = 6, String method = 6
Number 7: Math method = 7, String method = 7
Number 89: Math method = 17, String method = 17

Handling Edge Cases

// Test with numbers having same weights
const sameWeightTest = [13, 22, 31, 40]; // All have weight 4
console.log("Same weight test:", sortByWeight([...sameWeightTest]));

// Test with single digits
const singleDigits = [9, 3, 7, 1, 5];
console.log("Single digits:", sortByWeight([...singleDigits]));
Same weight test: [ 13, 22, 31, 40 ]
Single digits: [ 1, 3, 5, 7, 9 ]

Time and Space Complexity

Time Complexity: O(n × m × log n), where n is the array length and m is the average number of digits per number. The sorting operation is O(n log n), and each comparison involves calculating weights which takes O(m) time.

Space Complexity: O(log n) for the sorting algorithm's recursive calls.

Conclusion

We successfully created a function to sort numbers by their digit weights, with proper handling of equal weights by comparing numerical values. This approach works efficiently for reasonable-sized numbers and demonstrates custom sorting logic in JavaScript.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements