1

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 ?

2 Answers 2

1

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)

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

Comments

0

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

2 Comments

This is an array of primitive number. What I am looking for is a way to sort an array, Object like so : let arr = [{number:2},{number: 56},{number:12},{number:89},{number:21}]
ohh ok then wrap this in foreach methodand push values of numbers in any array then try sort

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.