0

I need to sort an array of objects by its values and I use this code to do this:

function compare(a,b){return dict[a]-dict[b]} Object.keys(dict).sort(compare)

it works if each value is different, but if two objects have the same value, it leaves them in the order they appear in the array but I want them to be sorted alphabetically. I couldn't figure out a way to do that.

dict = {a:1, d:4, c:2, b:4, e:5, f:3} should be :

{a:1, c:2, f:3, b:4, d:4, e:5 }

but I'm getting this:

{a:1, c:2, f:3, d:4, b:4, e:5 }
3
  • 1
    That's not even an array Commented Apr 21, 2020 at 13:07
  • 1
    Object.keys() returns an array, and you're sorting that array. The result will be an array, not an object. Commented Apr 21, 2020 at 13:07
  • so if the difference is zero, sort by the keys Commented Apr 21, 2020 at 13:08

2 Answers 2

1

You can change the compareFunction to use localeCompare

dict[a] - dict[b] || a.localeCompare(b)

If dict[a] - dict[b] returns 0, it checks the next condition and sorts the keys alphabetically

Here's a snippet:

const dict = {a:1, d:4, c:2, b:4, e:5, f:3}

function compare(a, b) {
  return dict[a] - dict[b] || a.localeCompare(b)
}

const sorted = Object.keys(dict)
                      .sort(compare)
                      .reduce((acc, k) => (acc[k] = dict[k], acc), {})

console.log( sorted )

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

Comments

1

So compare the keys if the diff is equal to zero

function compare(a, b) {
  var diff = dict[a] - dict[b]
  return diff === 0 ? a.localeCompare(b) : diff
}

const dict = {
  a: 1,
  d: 4,
  c: 2,
  b: 4,
  e: 5,
  f: 3
}

const result = Object.keys(dict).sort(compare).reduce((o, x) => ({
  ...o,
  [x]: dict[x],
}), {})

console.log(result)

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.