-
Notifications
You must be signed in to change notification settings - Fork 5
sort
Subhajit Sahu edited this page Mar 13, 2020
·
29 revisions
Sorts based on compare function (optional).
array.sort(x, [fn]);
// x: an array
// fn: compare function (a, b)
// --> sorted array
const array = require('extra-array');
var a = [-2, -3, 1, 4];
array.sort(a, (a, b) => a - b);
// [ -3, -2, 1, 4 ] (for nos. in JS, comparator is needed)
array.sort(a, (a, b) => Math.abs(a) - Math.abs(b));
// [ 1, -2, -3, 4 ]
var b = ['D', 'B', 'a', 'c'];
array.sort(b);
// [ 'B', 'D', 'a', 'c' ]
array.sort(b, (a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
// [ 'a', 'B', 'c', 'D' ]