简体   繁体   中英

Sort javascript object on multiple keys order by alphabet

Here is my js object:

var data = [
    { id: 7, name: "test1", sector: "A01" },
    { id: 7, name: "test2", sector: "C03" },
    { id: 8, name: "test4", sector: "B02" },
    { id: 8, name: "test5", sector: "A01" },
    { id: 8, name: "test6", sector: "C03" },
    { id: 7, name: "test3", sector: "B02" },
];

I want to sort this object by id and then by sector as below:

7,test1,A01
7,test3,B02
7,test2,C03
8,test5,A01
8,test4,B02
8,test6,C03

I have tried thenBy.js , the code is here , but the result is

7,test1,A01
7,test2,C03
7,test3,B02
8,test4,B02
8,test5,A01
8,test6,C03

How to fix it ?

If you can't see the output please go to External Resources on the left-side panel and add the following link for Firebug: getfirebug.com/firebug-lite-debug.js

I've had a look at your fiddle, and you're trying to subtract strings, which will result in NaN s, which can't really be used for sorting.

If you try using > or < when comparing the strings, it'll work.

Example:

firstBy(function (v1, v2) { return v1.id < v2.id ? -1 : (v1.id > v2.id ? 1 : 0); })
  .thenBy(function (v1, v2) { return v1.sector > v2.sector; });

This will yeild the result you're seeking.

You can do it without the firstBy().thenBy construct by simply concatenating the strings. The argument to the sort function will look like this:

function (v1, v2) { return v1.id + v1.sector < v2.id + v2.sector ? -1 : (v1.id + v1.sector> v2.id + v2.sector ? 1 : 0); }

Here is the fixed fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM