Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting elements in array based on their sum of number

I have been trying to solve an online Javascript challenge that i encountered. So, the problem is like this I have an array

let strng="103 123 4444 99 2000"

so i have to arrange them in ascending order based on sum of individual elements like

103=1+0+3=4
123=1+2+3=6
4444=4+4+4+4=16
99=9+9=18
2000=2+0+0+0=2

so now based on the results the elements in strng array needs to be sorted out in ascending order The final answer should be like

["2000" "103" "123" "4444" "99"]

so i tried and i reached a point from where i am totally confused as to what is the next step Below is my code

let s=[]

let f=strng.split(' ')
console.log(f)
f.map(item=>{
  let d=item.split('').reduce((a,b)=>Number(a)+Number(b),0)
  s.push(d)

  s.sort((a,b)=>a-b)


})
 console.log(s)     // gives me [2, 4, 6, 16, 18]

So i have sorted them acc. to sum of the digits of individual elements but now what or how should I arrange the elements in strng array ? I need to return the strng array by sorting in ascending order.so what are the next steps i would like to ask as a beginner i am totally stucked here .

like image 238
Ratnabh kumar rai Avatar asked Aug 31 '25 02:08

Ratnabh kumar rai


1 Answers

Your general approach is fine, but instead of using map, use sort. That's what it's for after all. :-) I'd also probably give myself a sumDigits function:

function sumDigits(str) {
    return str.split("").reduce((s, v) => s + Number(v), 0);
}

Then sort is roughly (array is the result of split(" ") on the original string):

array.sort((a, b) => sumDigits(a) - sumDigits(b));

Then presumably you need to join the result back into a single string via .join(" ").


Note that I didn't provide a complete, joined-up solution on purpose, because my sense is you want help figuring this out, not to have the solution handed to you. :-)

like image 138
T.J. Crowder Avatar answered Sep 04 '25 05:09

T.J. Crowder