如果你有一个需要排序的数组对象,然而之前,你可以使用原生函数 Array.sort 来进行一些漂亮的排序。在本文中,我将向您展示如何在 JavaScript 毫无麻烦和困扰的对数组对象进行排序。
阅读本文时,你需要一个基本的 JavaScript 概念的知识,比如声明变量,定义函数已经条件语句。我也会使用 ES6 语法。可以在这里查看更多 ES6 。
数组的基础排序
默认情况下,JavaScript Array.sort 将数组中的每个元素进行排序 ,转成字符串,并比较它们在 Unicode 表中的顺序。
const foo = [9, 2, 3, ‘random’, ‘panda’];
foo.sort();
// returns [ 2, 3, 9, ‘panda’, ‘random’ ]
const bar = [4, 19, 30, function(){}, {key: ‘value’}];
bar.sort();
// returns [ 19, 30, 4, { key: ‘value’ },[Function] ]
您可能想知道为什么 30 之前是 4 。没有逻辑啊。事实上,这是因为数组中的每个元素,首先转换为一个字符串,然后对 4 和 30 所对应的 Unicode 进行排序。
同样值得注意的是,与许多其他 JavaScript 数组函数不一样 。 Array.sort 实际上对数组排序进行了改变。
const baz = [‘hello world’, 31, 5, 9, 12];
baz.sort();
// baz 数组被修改了
console.log(baz);
// [12, 31, 5, 9, “hello world”]
为了避免这个问题,您可以创建一个新实例的数组进行排序和修改。
const baz = [‘hello world’, 31, 5, 9, 12];
// new instance of baz array is created and sorted
const newBaz = baz.slice().sort();
console.log(baz);
// “hello world”, 31, 5, 9, 12]
console.log(newBaz);
// [12, 31, 5, 9, “hello world”]
仅仅使用 Array.sort 对数组对象排序不会非常实用。 值得庆幸的是函数接受一个可选的 compareFunction 参数导致要排序的数组元素会根据根据函数返回值进行排序。
使用函数的比较功能
假设 a 和 b 是比较函数被对比的两个元素。如果返回值是以下情况:
1: 小于 0 a 在 b 之前
2: 大于 0 b 在 a 之前
3: 等于 0 a 等于 b
看一个简单的栗子:
const arr = [1,2,30,4];
function compare(a, b){
let comparison = 0;
if (a > b) {
comparison = 1;
} else if (b > a) {
comparison = -1;
return comparison;
arr.sort(compare);
// => 1, 2, 4, 30
上面的做法可以通过 a 减 b 进行重构
function compare(a, b){
return a – b;
修改成箭头函数:
arr.sort((a, b) => a – b));
在JavaScript对象数组进行排序
现在让我们来看看一个对象数组进行排序
const bands = [
{ genre: ‘Rap’, band: ‘Migos’, albums: 2},
{ genre: ‘Pop’, band: ‘Coldplay’, albums: 4},
{ genre: ‘Rock’, band: ‘Breaking Benjamins’, albums: 1}
];
我们可以用下面的比较函数根据类型对数组对象进行排序
function compare(a, b) {
// Use toUpperCase() to ignore character casing
const genreA = a.genre.toUpperCase();
const genreB = b.genre.toUpperCase();
let comparison = 0;
if (genreA > genreB) {
comparison = 1;
} else if (genreA < genreB) {
comparison = -1;
return comparison;
bands.sort(compare);
/* returns [
{ genre: ‘Pop’, band: ‘Coldplay’, albums: 4 },
{ genre: ‘Rap’, band: ‘Migos’, albums: 2 },
{ genre: ‘Rock’, band: ‘Breaking Benjamins’, albums: 1 }
] */
逆排序顺序,你可以简单地反转比较函数的返回值
function compare(a, b) {
…
//invert return value by multiplying by -1
return comparison * -1;
创建一个动态排序功能
我们创建一个排序函数,它可以用来排序数组对象,其值是字符串或数字。这个函数有两个参数,是我们要排序和结果的关键(升序或降序)。
const bands = [
{ genre: ‘Rap’, band: ‘Migos’, albums: 2},
{ genre: ‘Pop’, band: ‘Coldplay’, albums: 4, awards: 13},
{ genre: ‘Rock’, band: ‘Breaking Benjamins’, albums: 1}
];
// function for dynamic sorting
function compareValues(key, order=’asc’) {
return function(a, b) {
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn’t exist on either object
return 0;
const varA = (typeof a[key] === ‘string’) ?
a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === ‘string’) ?
b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
return (
(order == ‘desc’) ? (comparison * -1) : comparison
);
};
这是你如何使用它:
// array is sorted by band, in ascending order by default
bands.sort(compareValues(‘band’));
// array is sorted by band in descending order
bands.sort(compareValues(‘band’, ‘desc’));
// array is sorted by albums in ascending order
bands.sort(compareValues(‘albums’));
在上面的代码中,hasOwnProperty 方法是用来检查如果指定的属性上定义的每个对象并通过原型链没有继承。如果没有定义对象,函数返回0,导致排序顺序保持。
typeof 也用来检查值的数据类型。这使函数确定正确排序数组的方法。例如,如果指定属性的值是一个字符串,oUpperCase 方法可以将字符串转成大写,此时字符串排序可以不必在意大小写。
你可以调整上述函数以适应其他数据类型,和任何其他特性脚本的需求。
结论
现在你明白了吧 —— 一个简短的介绍一个对象数组进行排序。尽管许多 JavaScript 库提供这种动态排序的能力。自己实现这种功能也并不是很困难。
公众号
AutoHome
车服务前端团队
限时特惠:本站每日持续更新海量各大内部网赚创业教程,会员可以下载全站资源点击查看详情
站长微信:11082411