I have this array :
[ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]
and I would like to have :
[ [ 11, 'g' ], [ 9, 'e' ], [ 9, 'h' ], [ 3, 'i' ], [ 2, 'b' ], [ 1, 'a' ], [ 1, 'd' ], [ 1, 'f' ] ]
How can I do that with javascript please ?
I tried sort()
, I also tried with sort(compare)
with :
function compare(x, y) {
return x - y;
}
You can use .sort()
with Array Destructuring
like this:
function compare([a], [b]) {
return b - a;
}
Demo:
let a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]; a.sort(compare); function compare([a], [b]) { return b - a; } console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0; }
In case first elements match, you can sort based on 2nd element as well:
function compare([a, c], [b, d]) {
return (b - a) || c.localeCompare(d)
}
Demo:
let a = [ [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ], [ 1, 'a' ] ]; a.sort(compare); function compare([a, c], [b, d]) { return (b - a) || c.localeCompare(d); } console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0 }
You need to compare the first element in the nested array since you want to sort based on that number.
function compare(x, y) {
return y[0] - x[0];
}
var data = [ [1, 'a'], [2, 'b'], [1, 'd'], [9, 'e'], [1, 'f'], [11, 'g'], [9, 'h'], [3, 'i'] ]; function compare(x, y) { return y[0] - x[0]; } data.sort(compare); console.log(data);
In case you want to sort based on second element(secondary sorting in case the first element is same) then use String#localeCompare
method for comparing.
function compare(x, y) {
return y[0] - x[0] || x[1].localeCompare(y[0]);
}
var data = [ [2, 'b'], [1, 'd'], [9, 'e'], [1, 'f'], [1, 'a'], [11, 'g'], [9, 'h'], [3, 'i'] ]; function compare(x, y) { return (y[0] - x[0]) || x[1].localeCompare(y[1]); } data.sort(compare); console.log(data);
Compare the elements based on their first element, which is the number.
var a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]; a = a.sort((a,b) => { return b[0] - a[0] }); console.log(a)
Use sort
to compare first element and if first element is same then compare the second element .
arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) )
Demo
var arr = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]; arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) ); console.log(arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.