-1

There is an array which looks like this:

[
  { 
    _id: 'xxnQt5X8pfbcJMn6i',
    order: 2
  },
  { 
    _id: 'X8pfbcJxxnQt5Mn6i',
    order: 1
  },
  { 
    _id: 'Qt5X8pfxxnbcJMn6i',
    order: 3
  }
]

Now I need to sort the objects of this array by the order value. I tried to do this:

array.sort((a, b) => {
  return (a.order > b.order)
    ? 1
    : (b.order > a.order)
      ? -1
      : 0
})

But first it looks to me a bit to complicated for just sorting by an integer value and second it gives me the error TypeError: Cannot assign to read only property '1' of object '[object Array]'

user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

2

This can be achieved using Array.prototype.sort, no need for the further return conditions on the ternary operator, the array will implicitly be sorted by the first comparison:

console.log([
  { 
    _id: 'xxnQt5X8pfbcJMn6i',
    order: 2
  },
  { 
    _id: 'X8pfbcJxxnQt5Mn6i',
    order: 1
  },
  { 
    _id: 'Qt5X8pfxxnbcJMn6i',
    order: 3
  }
].sort((a, b) => a.order - b.order))

I can't reproduce the error that you're getting using the example provided though.

A. Bandtock
  • 1,233
  • 8
  • 14