Sorting a multidimensional array in JavaScript

I need to sort an array containing arrays in ascending numerical order. The data structure is as follows:

array = [[escalation],//integer
         [name],
         [email],
         [blackberry]];

I am trying to sort an array using this function (sort by escalation)

function sortfcn(a,b){
 if(a[0]<b[0]){
    return -1;
 }
 else if(a[0]>b[0]){
    return 1;
 }
 else{
    return 0;
 }
}

But my conclusion still looks incorrect ...

0 0 10 12 14 16 18 20 20 8

Any tips to fix this?

+3
source share
1 answer

From the sort output you provided, it looks like this: JavaScript reads the elements of the array as strings. See if parseInt works:

function sortfcn(a,b){
 if(parseInt(a[0])<parseInt(b[0])){
    return -1;
 }
 else if(parseInt(a[0])>parseInt(b[0])){
    return 1;
 }
 else{
    return 0;
 }
}
+1
source

Source: https://habr.com/ru/post/1758940/


All Articles