Search code examples
javascriptarraysmaxparseint

trying to figure out how to convert an array of strings to an array of numbers


i'm having issues figuring out how to transform an array of strings to an array of integers.

the following array for example :

['137','364','115','724']

What I essentially have to do is remove and return the largest number in each element and add it to the second largest number, the third largest number and so on depending on the length of the numbers. (The elements in the array will always be the same length)

for example:

1st largest number is 7, (remove largest number from each element leaving [13,34,11,24]) 2nd largest number left is 4 (remove largest number from each element again [1,3,1,2]) 3rd largest number left is 3 (no more numbers left to remove at this point)

7 + 4 + 3

This is what I have so far:

function sW(his) {
    // Write your code here
    for (var i = 0; i < history.length; i++ ){
        var something = history[i].split('')
        console.log(something)
        console.log(Math.max(parseInt(something)))
         console.log(parseInt(something))
    }
}

This isn't working so far because when I attempt to parseInt/ return the max of the number at each index, it will always just return the first number. Would appreciate some help, thanks!


Solution

  • Here's one solution:

    function slotWheels(arr) {
      // Sort all the numbers in the array
      // ['137','364','115','724'] -> ['731', '643', '511', '742']
      const sorted = arr.map(e => [...e].sort((a, b) => b - a).join(''));
      
      let sum = 0;
      for(let i = 0; i < sorted[0].length; i++) {
        // find out the max number of each numbers at the same position, and add it to sum
        sum += Math.max(...sorted.map(e => e[i]));
      }
      return sum;
    }
    
    console.log(slotWheels(['137','364','115','724']));