1

There are two arrays: The first one contain numbers, and the second one contains "weight" of the first array values.

It works like this:

arr1 = [56,65,100,89,180,90];

"Weight" of the numbers are calculated in this way:

 56 = 5+6 = 11;
 65 = 6+5 = 11;
 100 = 1+0+0 = 1; and so on..

So, arr2 = [11,11,1,17,9,9];

My question is how can I sort the values of the arr1 according to values of arr2?

I tried to modify simple bubble sort for this problem, but nothing changed.

function bubble(arr1, arr2) {
  var len = arr1.length;
  for (var i = 0; i < len; i++) {
    for (var j = 0; j < len - i - 1; j++) {
      if (arr2[j] > arr2[j + 1]) {
        var temp = arr1[j];
        arr1[j] = arr1[j + 1];
        arr1[j + 1] = temp;
      }
    }
  }
  return arr1;
}

arr1 = [56, 65, 100, 89, 180, 90];

arr2 = [11, 11, 1, 17, 9, 9];

console.log(bubble(arr1, arr2));

I expect the output of the bubble function to be [100,180,90,56,65,89]. This is why:

FirstArray -          [56,65,100,89,180,90] - arr1
"Weight of the values"[11,11, 1, 17, 9, 9 ] - arr2
Output                [100,180,90,56,65,89]
                      [1,  9,  9 ,11,11,17]
Nikhil
  • 6,493
  • 10
  • 31
  • 68
  • 1
    Possible duplicate of [Javascript - sort array based on another array](https://stackoverflow.com/questions/13304543/javascript-sort-array-based-on-another-array) – Prune Aug 21 '19 at 21:29
  • You have to sort *both arrays*, not just one. Otherwise the arrays start to missmatch and you get chaos – Jonas Wilms Aug 21 '19 at 21:36
  • @JonasWilms if second array is derived from first , then sorting arr1 alone works - https://codepen.io/nagasai/pen/WNeoaEv?editors=1010 – Naga Sai A Aug 21 '19 at 21:42
  • Why not just supply a comparison function and compute the "weight" during the sort? – Jim Mischel Aug 21 '19 at 21:43

2 Answers2

2

You can just calculate the weight on the fly while sorting:

const arr = [56,65,100,89,180,90];

arr.sort( (a,b) => 
  (a + '').split( '' ).reduce( (sum,x) => sum + +x, 0 ) -
  (b + '').split( '' ).reduce( (sum,x) => sum + +x, 0 )
);

console.log( arr );
Paul
  • 139,544
  • 27
  • 275
  • 264
0

To achieve expected result, use below option of sorrting arr1 with logic mentioned in question

  1. Sort arr1 bycomparing sum of digits
  2. Convert number to string and split it to array
  3. Use reduce sum all the digits and compare with the array elements

var arr1 = [56, 65, 100, 89, 180, 90];
var arr2 = [11, 11, 1, 17, 9, 9];

console.log(
  arr1.sort(
    (a, b) =>
      a
        .toString()
        .split("")
        .reduce((acc, v) => parseInt(acc) + parseInt(v)) -
      b
        .toString()
        .split("")
        .reduce((acc, v) => parseInt(acc) + parseInt(v))
  )
);

codepen - https://codepen.io/nagasai/pen/WNeoaEv?editors=1010

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40