mariocatch
mariocatch

Reputation: 8683

Sort an object of arrays in JavaScript

with an object like

{
 5: ['C','A','B'],
 8: ['E','F','D']
}

I'm trying to sort the arrays of each key, while returning the entire object. The above would come back looking like this:

{
 5: ['A','B','C'],
 8: ['D','E','F']
}

I've tried lots of variations of

Object.keys(myObj).map(k => { 
   return { k: myObj[k].sort() };
}

But this puts a literal k as each key instead of maintaining the keys from the original object. Not to mention this also creates an array of objects since map is returning an object for each key.

Edit:

I've found lots of "sort array of objects" - but not a "sort object of arrays" on SO - dupe and link if it already exists please.

Upvotes: 2

Views: 156

Answers (2)

Morlo Mbakop
Morlo Mbakop

Reputation: 3756

Try.

 const newSortedObj = Object.entries(yourObject).reduce((acc, [key, values]) => {
    acc[key] = values.sort((a, b) => a.localeCompare(b));

    return acc;
  }, {})

Do consider the locale and the character casing when you do string sort. Have a look at the local compare API

Upvotes: 2

Christian Carrillo
Christian Carrillo

Reputation: 2761

Using reduce:

const data = {
 5: ['C','A','B'],
 8: ['E','F','D']
}

let dataSort = Object.keys(data).reduce((acc, item) => {
  acc[item] = data[item].sort()  
  return acc
}, {})

console.log(dataSort)

Upvotes: 2

Related Questions