Daily Coding Challenge: Weight for weight – written in JavaScript

Posted by

2 min read ~ Hello readers! It’s really important for me to continue my practice and learning. Lately, I have been completing a coding challenge a day with codewars. This helps me keep my skills sharp and see how other devs all over the planet would solve these problems. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today. the problem set focuses on JavaScript and some of the important functions that we can leverage in our applications.

Weight for weight

My friend John and I are members of the “Fat to Fit Club (FFC)”. John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest.

I am the one who establishes the list so I told him: “Don’t worry any more, I will modify the order of the list”. It was decided to attribute a “weight” to numbers. The weight of a number will be from now on the sum of its digits.

For example 99 will have “weight” 18100 will have “weight” 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give 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"

When two numbers have the same “weight”, let us class them as if they were strings (alphabetical ordering) 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.

All numbers in the list are positive numbers and the list can be empty.

Notes:

it may happen that the input string have leading, trailing whitespaces and more than a unique whitespace between two consecutive numbers

JavaScript solution:

function orderWeight(strng) {
    // generate new obj
    let obj = {};
    // use truthy to check for value
    if (strng) {
        // split string and iterate over each index of integers
        strng.split(" ").forEach( (str) => {
            // convert the string into a number and reduce the numbers into one value
            let total = str.split('').map(Number).reduce((accumulator, currentValue) => accumulator + currentValue )
            // because JS only allows unique keys in objects, this lets us relate multiple 
            !obj[total] ? obj[total] = [str] : obj[total].push(str)
        });
    }
    
    let orderedObj = {};
    Object.keys(obj).sort().forEach( (key) => {
      orderedObj[key] = obj[key];
    });
    
    let finalArr = [];
    Object.keys(orderedObj).forEach( (key) => {
      orderedObj[key].length > 1 ? finalArr = [...finalArr, ...orderedObj[key].sort()] : finalArr.push(orderedObj[key][0])
    });
    
    return finalArr.join(' ')
}

The above algorithm was great fun to solve! Notably, because we get to use the reduce function to evaluate all of the potential integers that we are iterating over to get their sum.

The reduce() function reduces an array to a single value. For more info, visit this link to learn more about them.

After we have their sum, we can relate them back to their corresponding added values that we gathered originally from the input.

Disclaimer: *Now, as much as I am tempted to use ES8 & ES9 functions to reduce the number of lines in JavaScript, I am always a fan of readable code that others can understand. Therefore, with the JavaScript examples, I will try to write it without fancy functions as much as possible so it can actually be read and absorbed by my readers. All of my solutions are commented to explain my thinking. Of course, they could always be better. Please feel free to share how you would solve it!*

All credit to problem sets goes to codewars

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s