2017-03-22 4 views
0

私はこの配列を持っており、2番目の項目(newInv[x][1])でアルファベット順に並べ替える必要があります。私はcompareFunctionを作りましたが、うまくいきませんでした。助けて!ありがとう。.sort()2次元配列のjavascript

newInv = [ 
    [2, "Hair Pin"], 
    [3, "Half-Eaten Apple"], 
    [67, "Bowling Ball"], 
    [7, "Toothpaste"] 
]; 

答えて

0

あなたが間違って行ったことを特定するのは難しいですし、あなたが使用していないコードを含めていない理由を説明するのは難しいです。

しかし、あなたの問題はcompare関数を実装することにあったと思います。

  • 1(または任意の正の整数)最初の項目は、あなたのソート順
  • 後の第二の項目来る場合:比較関数は、二つの引数を取るためにあなたの配列から2つの項目がソートされている、と返す必要があります
  • 0最初の項目は、あなたのソート順に前に2番目の項目来る場合、彼らは「同じ」
  • -1(または任意の負の整数)であれば。ここで

何をしたいんコンペア機能である:

newInv = [ 
 
[2, "Hair Pin"], 
 
[3, "Half-Eaten Apple"], 
 
[67, "Bowling Ball"], 
 
[7, "Toothpaste"] 
 
]; 
 

 
compareFn = function(a, b) { 
 
    if (a[1] == b[1]) return 0; 
 
    return a[1] > b[1] ? 1 : -1; 
 
}; 
 

 
newInv.sort(compareFn); 
 

 
alert(newInv);

-1

newInv = [ 
    [2, "Hair Pin"], 
    [3, "Half-Eaten Apple"], 
    [67, "Bowling Ball"], 
    [7, "Toothpaste"] 
]; 

//classical nested loop for sorting 

for(i=0;i<newInv.length;i++) 
{ 
    for(j=i+1;j<newInv.length;j++) 
    { 
    //alphabetical comparing of second elements 

    if(newInv[i][1].localeCompare(newInv[j][1])>0) 
    { 
     //swapping values 
     var x=newInv[i]; 
     newInv[i]=newInv[j]; 
     newInv[j]=x; 
    } 
    } 
} 

//display sorted array 
console.log(newInv) 
+0

?説明してください。 –

1

あなたがソートされた配列を返すためにlocaleCompare()と組み合わせてsort()方法を使用することができます。なぜ反対票

var newInv = [ 
 
    [2, "Hair Pin"], 
 
    [3, "Half-Eaten Apple"], 
 
    [67, "Bowling Ball"], 
 
    [7, "Toothpaste"] 
 
]; 
 

 
var result = newInv.sort(function(a, b) { 
 
    return a[1].localeCompare(b[1]) 
 
}) 
 

 
console.log(result)