の例を用いてJavaScript配列ソート()メソッドで
まず、基本的な使い方
function compare(val1, val2) {
if (val1 > val2) {
return 1
} else if (val1 == val2) {
return 0
} else {
return -1
}
}
var array = [0, 5, 4, 3, 9, 10]
console.log(array.sort(compare))
// 输出[0, 3, 4, 5, 9, 10]
第二に、ソート対象の属性に従ってオブジェクト
function createComparisonFunction(propertyName) {
return function (object1, object2) {
let value1 = object1[propertyName]
let value2 = object2[propertyName]
if (value1 < value2) {
return -1
} else if (value1 > value2) {
return 1
} else {
return 0
}
}
}
let data = [
{
name: 'Links',
age: 28
},
{
name: 'Dolly',
age: 27
},
{
name: 'Rose',
age: 26
}
]
data.sort(createComparisonFunction("age"))
console.log(data)
// 输出
0: {name: "Rose", age: 26}
1: {name: "Dolly", age: 27}
2: {name: "Links", age: 28}
「JavaScriptの高度なプログラミング」からの例(第3版)