user13349816
user13349816

Reputation:

Sorting based on difference of the two arrays

I am having an array of arrays, where sorting needs to happen based on the difference of the element value.

The following is the sorting method that I have used:

let arr = [[20, 60], [10, 30], [40, 200], [90, 300]];
let res = arr.sort(function(a, b) {
  return a[1] - a[0] > b[1] - b[0];
});

The expected output should be

[[90,300], [40,200], [20,60], [10,30]]
//difference between elements are 210,160,40 and 20

Can someone help me ?

Upvotes: 0

Views: 253

Answers (2)

Md. Nurul Huda Riyad
Md. Nurul Huda Riyad

Reputation: 31

let arr = [[20, 60], [10, 30], [40, 200], [90, 300]];
let ans = arr.sort((a, b) => {
 return (Math.abs(b[0] - b[1])) - (Math.abs(a[0] - a[1]));
});
console.log(ans);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You need to take the delta of the deltas instead of returning a boolean value.

Array#sort sorts in situ.

let array = [[20, 60], [10, 30], [40, 200], [90, 300]];

array.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions