algorithm - What is the most compact way in JavaScript to sort an array of objects by a particular key, where the sorting order is defined in an array? -
this question has answer here:
here's mean. suppose have array of objects
var objs = [ { foo: 5, bar: "something"}, { foo: 4912, bar: "blah" }, { foo: -12, bar: "hehe" } ];
and array defines ordering on bar
values,
var arr = ["blah", "something", "hehe"]
does javascript have way of getting version of objs
to
[ { foo: 4912, bar: "blah" }, { foo: 5, bar: "something"} { foo: -12, bar: "hehe" } ];
???
the best way know like
objs.sort(function(x,y){ var ix = arr.indexof(x), iy = arr.indexof(y); if(ix<iy) return -1; else if(ix==iy) return 0; else return 1; });
but i'm wondering if there's way more compact.
you can refactor sort function:
objs.sort(function(x,y){ var ix = arr.indexof(x), iy = arr.indexof(y); return ix-iy; });
also, better performance may want rid of indexof functions, , load sort array hash:
var arr = { "blah" :0, "something":1, "hehe":2};
and sorting function this:
objs.sort(function(x,y){ return arr[x.bar]-arr[y.bar]; });
Comments
Post a Comment