user3142695
user3142695

Reputation: 17352

Move objects at the beginning of array using sort()

I need to sort an object array by date values:

array.sort(function(a,b){
return new Date(b.date) - new Date(a.date);
})

But if date is undefined, it should be placed at the beginning. With my code shown above, the empty datasets will be placed at the end.

Upvotes: 3

Views: 96

Answers (1)

user128511
user128511

Reputation:

const array = [
  { date: 624000, name: 'Eddison', },
  { date: 224000, name: 'Bobby', },
  {               name: '--no date 2' },
  { date: 924000, name: 'Fred', },
  { date: 124000, name: 'Abe', },
  {               name: '--no date 1' },
  { date: 424000, name: 'David', },
  { date: 324000, name: 'Catheryn', },
];

// assuming there is no 0 date
array.sort(function(a, b) {
  return (a.date && b.date)
      ? new Date(b.date) - new Date(a.date)
      : (a.date || 1) - (b.date || 1); 
});

//result
array.forEach(elem => console.log(JSON.stringify(elem)));

note if you care about the difference between a date of 0 and a undefined date then

  return (a.date !== undefined && b.date !== undefined)

Upvotes: 4

Related Questions