Skip to content
Advertisement

Javascript: sort Array of objects by external map (or external K.V pairs)

Pretty novice JavaScript user here. I questions of this type seem to be quite common, I promise I looked around for a while, although I may have missed something.

I am trying to sort an array of objects by values in a separate datastructure (map or object of k,v pairs)

Data to sort with (this is the result of Object.fromEntries(d3.rollup( ... )) to get occurrence counts of “foo”, “bar”, etc ):

dataSortBy = {bar:2, foo:3}

Alternatively the values to sort by could also be in map for if that is more appropriate (result of d3.rollup( ... )):

dataSortByMap =  {foo => 3, bar => 2}

Data to be sorted:

dataRaw = 
[
{name:"foo", relation:"baz"}
{name:"foo", relation:"buz"}
{name:"bar", relation:"baz"}
{name:"bar", relation:"buz"}
{name:"foo", relation:"biz"}
]

looking for result:

dataSorted = 
[
{name:"foo", relation:"baz"}
{name:"foo", relation:"buz"}
{name:"foo", relation:"biz"}
{name:"bar", relation:"baz"}
{name:"bar", relation:"buz"}
]

My approach so far is to follow https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#sorting_with_map

Thanks for any and all help. 🙂

Advertisement

Answer

Simply use the sortBy array in the .sort() callback function:

const dataRaw = 
[
{name:"foo", relation:"baz"},
{name:"foo", relation:"buz"},
{name:"bar", relation:"baz"},
{name:"bar", relation:"buz"},
{name:"foo", relation:"biz"}
], sortBy= {foo:3,bar:2};

console.log(dataRaw.sort((a,b)=>
 sortBy[a.name]-sortBy[b.name]))
Advertisement