1

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 alphabetically. I tried using a simple bubble sort technique to do it. 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??

Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
leoOrion
  • 1,833
  • 2
  • 26
  • 52

1 Answers1

2

You may use the build in method Array#sort with a custom callback.

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Just a few doubtss...What is a and b here. Is it two elements of the array in order?? – leoOrion May 10 '16 at 08:26
  • 1
    a and b are elements of the outer array, for example, it compares `[21, "Bowling Ball"]` against `[2, "Dirty Sock"]`. for the result, you need to access the second element of the inner array with the index. – Nina Scholz May 10 '16 at 08:28