Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort函数自定义排序 #18

Open
ttop5 opened this issue Feb 2, 2017 · 4 comments
Open

Sort函数自定义排序 #18

ttop5 opened this issue Feb 2, 2017 · 4 comments
Assignees
Milestone

Comments

@ttop5
Copy link
Owner

ttop5 commented Feb 2, 2017

JS中的sort函数是可以接收排序方法作为参数的,所以我们就利用这点来进行自定义排序。

1. 数组升序

const array = [1, 5, 2, 4, 3];

array.sort();

2. 数组降序

const array = [1, 5, 2, 4, 3];

function compare(a, b) {
  return b - a;
}

array.sort(compare);

3. 对象数组

将下面的对象根据年龄进行排序:

const friends = [
  { name: 'John', age: 30 },
  { name: 'Ana', age: 20 },
  { name: 'Tom', age: 25 },
];

function comparePerson(a, b) {
  return a.age - b.age;
}

friends.sort(comparePerson);

4. 字符串数组

const names = ['Ana', 'ana', 'john', 'John'];

names.sort();

上面的代码得到的结果是 ["Ana", "John", "ana", "john"],这是因为js在做字符比较的时候是根据字符对应的ASCII值来进行比较的,如:A, J, a, j 对应的ASCII值分别是 65, 75, 97, 106。

想要得到我们想要的 ["Ana", "ana", "John", "john"],只需要给sort传入一个忽略大小写的比较函数即可:

function stringCompare(a, b) {
  if (a.toLowerCase() < b.toLowerCase()) {
    return -1;
  }
  if (a.toLowerCase() > b.toLowerCase()) {
    return 1;
  }
  return 0;
}

names.sort(stringCompare);
@ttop5 ttop5 added this to the 2017年02月 milestone Feb 2, 2017
@ttop5 ttop5 self-assigned this Feb 2, 2017
@junnplus
Copy link

junnplus commented Feb 3, 2017

function compare(a, b) {
  return a - b;
}

这样写省事多了

@ttop5
Copy link
Owner Author

ttop5 commented Feb 3, 2017

@junnplus get 🌹

@ttop5 ttop5 closed this as completed Aug 8, 2017
@ttop5 ttop5 reopened this Jun 28, 2019
@junnplus
Copy link

最近写前端用lodash感觉很舒服。。。

@ttop5
Copy link
Owner Author

ttop5 commented Jun 28, 2019

@junnplus 全栈大佬

@ttop5 ttop5 changed the title sort函数自定义排序 Sort函数自定义排序 Jul 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants