-1

I have an array of objects like the one below. Although, the order isn't in ascending or descending. Is there function that sorts the numbers in each object and replacing it into a new array or something similar?

let array = [
  {
    number: 16
  },
  {
    number: 25
  },
  {
    number: 20
  },
  {
    number: 28
  }
];
Phil
  • 157,677
  • 23
  • 242
  • 245
Jeffplays2005
  • 172
  • 15

1 Answers1

1

Yes, you can use array.sort() on a copy of your array.

example:

let newArray = [...array].sort((a, b) => a.number - b.number)

That will sort your array ascending. If you want it descending just switch to b.number - a.number

More info on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Thomas Bay
  • 609
  • 4
  • 13