Skip to content
Subhajit Sahu edited this page May 3, 2023 · 19 revisions

Arrange values in order!

Alternatives: sort, sort$.
Similar: sort, rangedSort, partialSort, rangedPartialSort.


function sort$(x, fc, fm, fs)
// x:  an array (updated!)
// fc: compare function (a, b)
// fm: map function (v, i, x)
// fs: swap function (x, i, j)
const xarray = require('extra-array');


// Sort using default comparison!
var x = [-2, -3, 1, 4];
xarray.sort$(x);
// → [ -3, -2, 1, 4 ]  (compares numbers, x is updated!)
x;
// → [ -3, -2, 1, 4 ]


// Sort using absolute comparison!
var x = [-2, -3, 1, 4];
xarray.sort$(x, (a, b) => Math.abs(a) - Math.abs(b));
// → [ 1, -2, -3, 4 ]  (x is updated!)


// Sort using absolute values!
var x = [-2, -3, 1, 4];
xarray.sort$(x, null, v => Math.abs(v));
// → [ 1, -2, -3, 4 ]


// Sort two arrays together!
var x = ['b', 'a', 'd', 'c'];
var y = [2, 1, 4, 3];
xarray.sort$(x, null, null, (x, i, j) => {
  xarray.swap$(x, i, j);
  xarray.swap$(y, i, j);
});
x;
// → [ 'a', 'b', 'c', 'd' ]
y;
// → [ 1, 2, 3, 4 ]


References

Clone this wiki locally