0

I'm trying to sort a list of objects based on the appearance of a key in an external object. For some reason, I'm not able to sort the array and I tried using lodash or other methods..

Here's a more simple example:

arr = [1, 2, 3, 4, 5, 6]
obj = { 4: true, 6: true }

arr.sort((a, b) => obj[a] - obj[b])
// [1, 2, 3, 4, 5, 6]

I would like the truth-y values to be first, as in [4, 6, 1, 2, 3, 5]

Why doesn't this work?

0

1 Answer 1

3

You can't subtract true and undefined (which is the value for keys that don't exist).

> arr.sort((a, b) => (obj[b] || 0) - (obj[a] || 0))
(6) [4, 6, 1, 2, 3, 5]

works instead (i.e. coercing that undefined to zero).

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.