0

I have an array of object and want to reorder objects inside array Is there any way to do that?

var obj = [ {start: 12, end: 14}, {start: 2, end:8}]

I should check if start date of first object is greater than second object's start date and change objects order, The result in this case should be =>

var obj = [ {start: 2, end:8}, {start: 12, end: 14}]

I know about sorting inside object but cant find way to reorder the whole object.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 4
    Does this answer your question? [Sorting an array of objects by property values](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) – Shubham Sharma Dec 07 '20 at 15:20
  • Take a look at `Array.prototype.sort` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Andreas Louv Dec 07 '20 at 15:20
  • That solved my problem thanks –  Dec 07 '20 at 15:23
  • Please don't remove the before and after code samples; these are required to get good answers and to identify good duplicate questions. – Heretic Monkey Dec 07 '20 at 15:25

1 Answers1

0

Use your expeceted property to conduct compared function

var obj = [
  { start: 12, end: 14 },
  { start: 2, end: 8 },
]

const res = obj.sort((a, b) => a.start - b.start)

console.log(res)
hgb123
  • 13,869
  • 3
  • 20
  • 38
  • Always good to have a warning that `Array.prototype.sort` is *in place* and does modify the array that is being sorted (and not just the returned array). – crashmstr Dec 07 '20 at 15:23