4

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 .

4
  • let strng=["103" "123" "4444" "99" "2000"] is a syntax error. Are you doing an array with five entries, or something else? Commented Jan 12, 2020 at 14:57
  • actually it was like let strng="103 123 4444 99 2000" so i did strng.split(' ') to convert to array Commented Jan 12, 2020 at 14:58
  • I changed my answer, now it preserve natural order when the digit's sum is equal Commented Jan 12, 2020 at 18:19
  • what about order between 321 / 312 / 123 which one come first ? Commented Jan 12, 2020 at 20:36

7 Answers 7

4

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. :-)

Sign up to request clarification or add additional context in comments.

Comments

1

Here's my solution:

const string = "103 123 4444 99 2000".split(' ');
const sumString = (str) => str.split('').reduce((s, c) => s + Number(c), 0)

string.sort((a, b) => {
    return sumString(a) - sumString(b);
});

console.log(string); //["2000", "103", "123", "4444", "99"]

Comments

1

Maybe like this:

   let strng="103 123 4444 99 2000";

   var string_arr = strng.split(' ');
   for(var key_sa in string_arr){
   	   var cur_str = string_arr[key_sa];
   	   var cur_str_arr =  cur_str.split('');
   	   var cur_str_sum = 0;
   	   for(var key_csa in cur_str_arr){
   	   	    cur_str_sum += parseInt(cur_str_arr[key_csa]) || 0;
   	   }
   	   console.log(cur_str_sum);
   }

Comments

1

my 2 cents (ninja code ?)

the idea made its way, I ended up realizing that the "321" and "123" are on the same sum (6);
ditto for "4444" and "88" or even "2000" and "2"...
In these cases of equality it was necessary to preserve the natural order

i.e:

sortStrArray('103 123 4444 99 20') -> '20 103 123 4444 99'
sortStrArray('2000 99 123 4444 2') -> '2 2000 123 4444 99'
sortStrArray('321 4444 123 88 99') -> '123 321 88 4444 99' 

const sum =s=>[...s].reduce((t,x)=>t+(+x),0)
  ,   sortStrArray =s=>s.split(' ').sort((a,b)=>{r=sum(a)-sum(b);return (r?r:(+a)-(+b))}).join(' ')
  ;

const values= [ '103 123 4444 99 20'
              , '2000 99 123 4444 2'
              , '321 4444 123 88 99'
              ];

// proof (run snippeet)
values.forEach(val=>console.log(`sortStrArray('${val}') -> '${sortStrArray(val) }'`))
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

@Ratnabhkumarrai I changed my answer, i made it in a function ( named sortStrArray)
1

You could split the problem into smaller parts, like one function for getting the sum or one to store the sum for a given string to prevent summing the same string over an over.

At last take a sort by using the precalculated sums.

let sum = s => Array.from(s, Number).reduce((a, b) => a + b, 0),
    strings = ["103", "321", "123", "4444", "99", "2000", "20"],
    sums = strings.reduce((m, s) => m.set(s, sum(s)), new Map);

strings.sort((a, b) => sums.get(a) - sums.get(b));

console.log(strings);

Comments

1

Please check the below snippet. It might help.

function arrangeNums(s) {
   function getSum(num) {
    return num.split('').map(n => parseInt(n)).reduce((acc, curr) => acc + curr, 0);
   }
   
   return s.split(' ').sort((a,b) => getSum(a) - getSum(b)).join(' ');
}

let strng="103 321 123 4444 99 2000 20";
console.log(arrangeNums(strng));

Comments

1

Functional style of code.

str.split(/\s+/)
   .map(a => [a, 
              a.split('')
               .reduce((acc, b) => acc + Number(b), 0)])
   .sort((a, b) => a[1] -  b[1])
   .map(e => e[0])

let str = "103 321 123 4444 99 2000 20"

let res = str.split(/\s+/)
            .map(a => [a
                      ,a.split('')
                        .reduce((acc, b) => acc + Number(b), 0)
                      ])
            .sort((a, b) => a[1] -  b[1])
            .map(e => e[0])
            
 console.log(res)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.