0

I'm trying to sort a map by value where the values are arrays.

For example the map below:

{'let1': ['art', 'can'], 'let2': ['own', 'kit', 'dig'], 'let3': ['art', 'zero']}

I would like to sort it as:

{'let1': ['art', 'can'], 'let3': ['art', 'zero'], 'let2': ['own', 'kit', 'dig']}

Is it possible using the JavaScript sort() method?

2
  • 1
    What are you actually trying to achieve? Can you show us a bigger picture? It might be an XY problem Commented Aug 3, 2020 at 19:16
  • What do you need this for? Commented Aug 3, 2020 at 19:16

1 Answer 1

3

Sorting of an object is not advised. It should be treated as a look-up. You should convert the key-value pairs to entry tuples and sort the value at index 1 (aka the value array).

See: Sorting object property by values

let obj = {
  'let1': ['art', 'can'],
  'let2': ['own', 'kit', 'dig'],
  'let3': ['art', 'zero']
};

console.log(Object.entries(obj).sort((a, b) =>
  a[1].join(',').localeCompare(b[1].join(','))));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Result

[
  [ "let1", [ "art", "can"        ] ],
  [ "let3", [ "art", "zero"       ] ],
  [ "let2", [ "own", "kit", "dig" ] ]
]
Sign up to request clarification or add additional context in comments.

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.