Sort 2d arrays containing numbers and strings

I have an inventory as shown below.

var arr1 = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

I want to sort the inventory in alphabetical order. I tried using an easy way to sort the bubbles to do this. But it shows an error: "wrappedCompareFn is not a function."

function sort(arr1){    
//console.log("works");
for(var i=0;i<arr1.length;i++){      
  for(var j=0;j<arr1.length;j++){     
   // console.log(arr1[j][1].localeCompare(arr1[i][1]));
    if(arr1[j][1].localeCompare(arr1[i][1])<0){          
      var tmp=arr1[i][1];
      arr1[i][1]=arr1[j][1];
      arr1[j][1]=tmp;          
       }          
    }      
  }        
return arr1;
}

Is there a problem with my code? Also is there a better way to sort multidimensional arrays with different types of objects?

+1
source share
1 answer

You can use the build method Array#sortwith a custom callback.

sort() . . Unicode.

var arr1 = [[1, "Hair Pin"], [21, "Bowling Ball"], [2, "Dirty Sock"], [5, "Microphone"]];

arr1.sort(function (a, b) {
    return a[1].localeCompare(b[1]);
});

document.write('<pre>' + JSON.stringify(arr1, 0, 4) + '</pre>');
Hide result
+1

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


All Articles