2

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.

2
  • 1
    do return { [k]: myObj[k].sort() }; Commented Aug 16, 2019 at 2:45
  • Thank you, that does solve the literal k issue. However the result of the map above is an array of objects, instead of an object of arrays (I realize that's how map works) Commented Aug 16, 2019 at 2:48

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.