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]]
];
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With