JavaScript Array sort 方法

JavaScript About 1,087 words

正序

前者-后者

const arr = [
    {amount: 39.9, name: "product c"},
    {amount: 19.9, name: "product a"},
    {amount: 29.9, name: "product b"},
];
const sortedArr1 = arr.sort((a, b) => a.amount - b.amount);
console.log(sortedArr1)

输出

[
    {
        "amount": 19.9,
        "name": "product a"
    },
    {
        "amount": 29.9,
        "name": "product b"
    },
    {
        "amount": 39.9,
        "name": "product c"
    }
]

倒叙

后者-前者

const arr = [
    {amount: 39.9, name: "product c"},
    {amount: 19.9, name: "product a"},
    {amount: 29.9, name: "product b"},
];

const sortedArr2 = arr.sort((a, b) => b.amount - a.amount);
console.log(sortedArr2)
[
    {
        "amount": 39.9,
        "name": "product c"
    },
    {
        "amount": 29.9,
        "name": "product b"
    },
    {
        "amount": 19.9,
        "name": "product a"
    }
]

基础类型的 sort

const numbers = [3, 5, 6, 1, 3].sort();
console.log(numbers)
const numbers1 = [3, 5, 6, 1, 3].sort((a, b) => b -a);
console.log(numbers1)

输出

[
    1,
    3,
    3,
    5,
    6
]

[
    6,
    5,
    3,
    3,
    1
]
Views: 27 · Posted: 2025-12-02

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today In History
Browsing Refresh