node.js - Node js natural sort on array of objects based on string and numeric key values -


i have array of object string , numeric values. need natural sort work on combined values. example:

input array:

[ {      key1: '156557_08_315f036d',     key2: 30,     key3: 's' },   {      key1: '156557_08_315f036d',     key2: 10,     key3: 'm' },  {      key1: '156557_08_315f036d',     key2: 10,     key3: 's' },   {      key1: '156557_08_315f036d',     key2: 15,     key3: 's' },   {      key1: '156557_08_315f036d',     key2: 20,     key3: 's' } ] 

this should sorted in ascending order of key3+key1+key2 format, key2 numeric , wants sorted naturally..not string.

output be:

[ {      key1: '156557_08_315f036d',     key2: 10,     key3: 'm' }, {      key1: '156557_08_315f036d',     key2: 10,     key3: 's' }, {      key1: '156557_08_315f036d',     key2: 15,     key3: 's' }, {      key1: '156557_08_315f036d',     key2: 20,     key3: 's' }, {      key1: '156557_08_315f036d',     key2: 30,     key3: 's' } ]  arr.sort(function (a, b) {     return (       a.key3 + a.key1 + parseint(a.key2) >       b.key3 + b.key1 +  parseint(b.key2) ?       1 :       ((b.key3 + b.key1 +  parseint(b.key2) >         a.key3 + a.key1 +  parseint(a.key2)) ?       -1 : 0));   }); 

tried tostring of key2, did string sort.

if don't mind dependency, here's cool library called thenby:

// first length of name, population, id data.sort(     firstby(function (v) { return v.name.length; })     .thenby("population")     .thenby("id") ); 

this sorts using function, or key name of object property.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -