Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort an array of arrays by child array

How can I sort an array of arrays by the second element which is also an array that contains only one element?

For example, the following array

array = [
    ["text", ["bcc"], [2]],
    ["text", ["cdd"], [3]],
    ["text", ["aff"], [1]],
    ["text", ["zaa"], [5]],
    ["text", ["d11"], [4]]
];

Should be sorted as follows:

sorted_array = [
    ["text", ["aff"], [1]],
    ["text", ["bcc"], [2]],
    ["text", ["cdd"], [3]],
    ["text", ["d11"], [4]],
    ["text", ["zaa"], [5]]
];
like image 314
Valip Avatar asked Mar 09 '23 20:03

Valip


1 Answers

You should use .sort() method which accepts a callback function.

Also, you have to use .localeCompare method in order to compare two strings.

array = [
    ["text", ["bcc"], [1]],
    ["text", ["cdd"], [1]],
    ["text", ["aff"], [1]],
    ["text", ["zaa"], [1]],
    ["text", ["d11"], [1]]
];
var sortedArray=array.sort(callback);
function callback(a,b){
  return a[1][0].localeCompare(b[1][0]);
}
console.log(sortedArray);
like image 140
Mihai Alexandru-Ionut Avatar answered Mar 21 '23 00:03

Mihai Alexandru-Ionut