CitizenFiftyTwo
CitizenFiftyTwo

Reputation: 849

How do you sort a list of Object?

I am looking for a solution to compare two instances of an Oject so instead of

list.sort((a, b) => (a.number > b.number) ? 1 : -1)

I can have simply have list.sort()

Is it possible ?

Upvotes: 1

Views: 52

Answers (2)

Nino Filiu
Nino Filiu

Reputation: 18493

The doc say that in arr.sort([compareFunction]), if compareFunction is omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value, so it's not suited for a list of object.

But really, you should stick to precising a compare function, sorting by object key is really not verbose:

const arr = [
  { number: 10 },
  { number: 20 },
  { number: 0 },
  { number: 30 },
]
arr.sort((a,b) => a.number - b.number)
console.log(arr)

Upvotes: 1

arslan
arslan

Reputation: 1144

let arr = [2,56,12,89,21]
arr.sort(function(a, b){return a-b});

did you try this one? because we should always return a+b or a-b in sort method otherwise this will not effectable i think

Upvotes: 0

Related Questions