EN
JavaScript - sort array of arrays by string in it
1 answers
0 points
I have an array that contains arrays and I would like to sort the arrays in order based on a certain string within those arrays.
For example:
xxxxxxxxxx
1
var array = [
2
[3, 'Kate', '...'],
3
[1, 'Tom', '...'],
4
[2, 'Ann', '...'],
5
[4, 'Mark', '...'],
6
];
I want it to be sorted alphabetically by name in the following order:
xxxxxxxxxx
1
[
2
[ 2, 'Ann', '...' ],
3
[ 3, 'Kate', '...' ],
4
[ 4, 'Mark', '...' ],
5
[ 1, 'Tom', '...' ]
6
]
1 answer
0 points
You can pass a custom compare function to the sort()
method.
Practical examples
ES6+ solution:
xxxxxxxxxx
1
let array = [
2
[3, 'Kate', '...'],
3
[1, 'Tom', '...'],
4
[2, 'Ann', '...'],
5
[4, 'Mark', '...'],
6
];
7
8
array = array.sort((a, b) => (a[1] < b[1] ? -1 : 1));
9
10
console.log(JSON.stringify(array, null, 4));
For older versions:
xxxxxxxxxx
1
function compareFunction(a, b) {
2
if (a[1] < b[1]) return -1;
3
if (a[1] > b[1]) return 1;
4
return 0;
5
}
6
7
var array = [
8
[3, 'Kate', '...'],
9
[1, 'Tom', '...'],
10
[2, 'Ann', '...'],
11
[4, 'Mark', '...'],
12
];
13
14
array = array.sort(compareFunction);
15
16
console.log(JSON.stringify(array, null, 4));
See also
References
0 commentsShow commentsAdd comment