Sort javascript object on multiple keys order by alphabet

246 views Asked by At

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

2

There are 2 answers

1
Thor Jacobsen On

I've had a look at your fiddle, and you're trying to subtract strings, which will result in NaNs, 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.

0
Pascal Rosin On

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.