## Javascript一维数组和对象数组排序方案

Wonfody 2020-11-13 18:57:13
javascript 数组 排序 对象

## 一、普通一维数组

js中用 `sort()` 方法为数组排序。`sort()` 方法有一个可选参数，是用来确定元素顺序的函数。如果这个参数被省略，那么数组中的元素将按照ASCII字符顺序进行排序。如：

``````var arr = ["a", "A", "c", "B"];
arr.sort();
console.log(arr); // ["A", "B", "a", "c"]``````

``````var arr = [15, 8, 25, 3];
arr.sort();
console.log(arr); // [15, 25, 3, 8]``````

``````var arr = [23, 9, 4, 78, 3];
// 比较函数
var compare = function (x, y) {
if (x < y) {
return -1;
} else if (x > y) {
return 1;
} else {
return 0;
}
}
console.log(arr.sort(compare));``````

``````var compare = function (x, y) {
if (x < y) {
return 1;
} else if (x > y) {
return -1;
} else {
return 0;
}
}``````

``````var arr = ["b", 5];
console.log(arr.sort(compare))``````

## 二、数组对象

``````var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (obj1, obj2) {
var val1 = obj1.name;
var val2 = obj2.name;
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
console.log(arr.sort(compare));``````

``````var compare = function (prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}``````

``var arr = [{name: "zlw", age: "24"}, {name: "wlz", age: "5"}];``

``[Object { name="zlw", age="24"}, Object { name="wlz", age="5"}]``

``````var compare = function (prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}``````

``[Object { name="wlz", age="5"}, Object { name="zlw", age="24"}]``

https://segmentfault.com/a/1190000038163835