0

I have this array:

[
  ["name1", { count: 20 }],
  ["name2", { count: 10 }]
]

How would I go about sorting this array by the value of count?

I have tried using the sort function,

const sort = Array.sort((a, b) => b.count - a.count);

But this didn't change anything.

1 Answer 1

2

You need to access the second entry in the arrays inside the outer array. Your code is using count on the array entries, but they don't have a count property:

theArray.sort((a, b) => b[1].count - a[1].count);

Note also that you call sort on the actual array, not the Array constructor. It also sorts the array in-place, rather than returning a sorted array (it also returns the array you call it on, though).

Live Example:

const theArray = [
  ["name1", { count: 20 }],
  ["name2", { count: 10 }],
  ["name3", { count: 15 }]
];
console.log("before:", theArray);
theArray.sort((a, b) => b[1].count - a[1].count);
console.log("after:", theArray);
.as-console-wrapper {
    max-height: 100% !important;
}

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

2 Comments

It might be better to use console.log("after:", theArray) in your example and scrap the sort variable. This would show the in-place behaviour of sort(). By capturing the return value inside a new variable, newcomers to JavaScript might think that it returns a sorted array and leaves the original array untouched.
@3limin4t0r - Yeah, that's a good point. I just minimally changed the OP's code, but I agree that it's better not to give the wrong impression.

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.