WePuri
ワードプレス教室

WePuri
ワードプレス教室

MENU
[bogo]

sort 並び替えまとめ

1次元配列をsortで並べ替え

文字列の場合

// 通常の並び(昇順)
const list_1 = ['お','え','あ','い','う']
list_1.sort()
console.log(list_1)

// 逆に並べる(降順)
const list_1_b = ['お','え','あ','い','う']
list_1_b.sort((a, b) => {
    b.localeCompare(a), 'ja'
})
console.log(list_1_b)

数字の場合

// 通常の並び(昇順)
const list_2 = [1,5,8,10,4,3]
list_2.sort((a,b)=>{
    return a - b
})
console.log(list_2)

// 逆に並べる(降順)
const list_2_b = [1,5,8,10,4,3]
list_2_b.sort((a,b)=>{
    return b - a
})
console.log(list_2_b)

2次元配列をsortで並べ替え

配列の1番目(0番目)の数字を基準に並べ替え(昇順)

const list_3 = [
    [5 , 6 , 7],
    [10 , 5 , 4],
    [4 , 4 , 3],
    [12 , 7 , 7],
]
list_3.sort((a,b)=>{
    return a[0] - b[0]
})
console.log(list_3)

配列の2番目(1番目)の数字を基準に並べ替え(昇順)

const list_3_b = [
    [5 , 6 , 7],
    [10 , 5 , 4],
    [4 , 4 , 3],
    [12 , 7 , 7],
]
list_3.sort((a,b)=>{
    return a[1] - b[1]
})
console.log(list_3_b)

連想配列の場合(オブジェクト)

年齢順に並べ替え(昇順)

const list_4 = [
    {
        "name":"aoki",
        "age":"45",
        "sex":"women"
    },
    {
        "name":"oki",
        "age":"21",
        "sex":"men"
    },
    {
        "name":"sato",
        "age":"25",
        "sex":"women"
    },
    {
        "name":"sakai",
        "age":"13",
        "sex":"men"
    },
]
list_4.sort((a,b)=>{
    return a.age - b.age
})
console.log(list_4)

日付の並べ変え(オブジェクト)

const list_5 = [
    {
        "name": "aoki",
        "age": "45",
        "sex": "women",
        "day": "2020.01.01"
    },
    {
        "name": "oki",
        "age": "21",
        "sex": "men",
        "day": "2021.07.01"
    },
    {
        "name": "sato",
        "age": "25",
        "sex": "women",
        "day": "2019.05.30"
    },
    {
        "name": "sakai",
        "age": "13",
        "sex": "men",
        "day": "2020.01.25"
    },
]
list_5.sort((a, b) => {
    let x = new Date(a.day),
        y = new Date(b.day);
    return x - y;
})
console.log(list_5)

ひらがなの並び替え(オブジェクト)

const list_6 = [
    {
        "name": "いしかわ",
        "age": "45",
        "sex": "women",
        "day": "2020.01.01"
    },
    {
        "name": "おおき",
        "age": "21",
        "sex": "men",
        "day": "2021.07.01"
    },
    {
        "name": "あいだ",
        "age": "25",
        "sex": "women",
        "day": "2019.05.30"
    },
    {
        "name": "わかつき",
        "age": "13",
        "sex": "men",
        "day": "2020.01.25"
    },
]

list_6.sort(function(b,a){
   if (a.name > b.name ) return -1;
   if (b.name > a.name ) return 1;
   return 0;
})
console.log(list_6)