私はこの配列を持っており、2番目の項目(newInv[x][1])
でアルファベット順に並べ替える必要があります。私はcompareFunction
を作りましたが、うまくいきませんでした。助けて!ありがとう。.sort()2次元配列のjavascript
newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
私はこの配列を持っており、2番目の項目(newInv[x][1])
でアルファベット順に並べ替える必要があります。私はcompareFunction
を作りましたが、うまくいきませんでした。助けて!ありがとう。.sort()2次元配列のjavascript
newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
あなたが間違って行ったことを特定するのは難しいですし、あなたが使用していないコードを含めていない理由を説明するのは難しいです。
しかし、あなたの問題はcompare関数を実装することにあったと思います。
1
(または任意の正の整数)最初の項目は、あなたのソート順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);
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)
あなたがソートされた配列を返すために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)
?説明してください。 –