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 .
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With