最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sorting elements in array based on their sum of number - Stack Overflow

programmeradmin3浏览0评论

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 .

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 .

Share Improve this question edited Jan 12, 2020 at 14:59 RRR uzumaki asked Jan 12, 2020 at 14:55 RRR uzumakiRRR uzumaki 1,3284 gold badges28 silver badges63 bronze badges 4
  • let strng=["103" "123" "4444" "99" "2000"] is a syntax error. Are you doing an array with five entries, or something else? – T.J. Crowder 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 – RRR uzumaki Commented Jan 12, 2020 at 14:58
  • I changed my answer, now it preserve natural order when the digit's sum is equal – Mister Jojo Commented Jan 12, 2020 at 18:19
  • what about order between 321 / 312 / 123 which one e first ? – Mister Jojo Commented Jan 12, 2020 at 20:36
Add a ment  | 

7 Answers 7

Reset to default 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 plete, joined-up solution on purpose, because my sense is you want help figuring this out, not to have the solution handed to you. :-)

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"]

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);
   }

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; }

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);

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));

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)

发布评论

评论列表(0)

  1. 暂无评论