Help us understand the problem. What is going on with this article?

JavaScript つい忘れてしまう配列のソート方法

More than 5 years have passed since last update.

いつも忘れてググルので、ここにメモしておきます。

1次元配列のソート

昇順ソート

var a = [5,3,9,1,10]
a.sort(function(a,b){
        if( a < b ) return -1;
        if( a > b ) return 1;
        return 0;
});
結果:1,3,5,9,10

降順ソート

var a = [5,3,9,1,10]
a.sort(function(a,b){
        if( a > b ) return -1;
        if( a < b ) return 1;
        return 0;
});
結果:10,9,5,3,1

連想配列の特定のキーでソート

昇順

//フルーツの名前と価格。価格でソートする
var fruits = [
   {name:"apple",price:100},
   {name:"orange",price:98},
   {name:"banana",price:50},
   {name:"melon",price:500},
   {name:"mango",price:398}
]

fruits.sort(function(a,b){
    if(a.price<b.price) return -1;
    if(a.price > b.price) return 1;
    return 0;
});
console.log(fruits)

結果
[ { name: 'banana', price: 50 },
  { name: 'orange', price: 98 },
  { name: 'apple', price: 100 },
  { name: 'mango', price: 398 },
  { name: 'melon', price: 500 } ]

降順

fruits.sort(function(a,b){
    if(a.price>b.price) return -1;
    if(a.price < b.price) return 1;
    return 0;
});
console.log(fruits);
結果
[ { name: 'melon', price: 500 },
  { name: 'mango', price: 398 },
  { name: 'apple', price: 100 },
  { name: 'orange', price: 98 },
  { name: 'banana', price: 50 } ]

連想配列の複数のキーでソート

//フルーツの価格と重さ。
var fruits = [
   {name:"apple",price:100,weight:90},
   {name:"mango",price:500,weight:200},  
   {name:"orange",price:98,weight:150},
   {name:"apple",price:100,weight:100}, 
   {name:"banana",price:50,weight:50},
   {name:"melon",price:500,weight:500},
   {name:"mango",price:398,weight:200}
]

//重さ、価格、の順に並び替え(降順)

fruits.sort(function(a,b){
    if(a.weight>b.weight) return -1;
    if(a.weight<b.weight) return 1;
    if(a.price>b.price) return -1;
    if(a.price < b.price) return 1;
    return 0;
});

結果
[ { name: 'melon', price: 500, weight: 500 },
  { name: 'mango', price: 500, weight: 200 },
  { name: 'mango', price: 398, weight: 200 },
  { name: 'orange', price: 98, weight: 150 },
  { name: 'apple', price: 100, weight: 100 },
  { name: 'apple', price: 100, weight: 90 },
  { name: 'banana', price: 50, weight: 50 } ]

これであってるよね?
間違いがありましたら、ご指摘ください。

関連リンク

あれ?昇順てどっちだっけ?降順てどっちだっけ?

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away