623

More than 5 years have passed since last update.

posted at

updated at

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

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

# 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;
});

``````

## 降順ソート

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

``````

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

## 昇順

``````//フルーツの名前と価格。価格でソートする
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 } ]
``````

これであってるよね？

# 関連リンク

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

Register as a new user and use Qiita more conveniently

1. You get articles that match your needs
2. You can efficiently read back useful information
What you can do with signing up
623