POV
POV

Reputation: 12005

How to move all element in array to bottom if?

How to move all elements in an array to the bottom if the element of an array(object) not have field date?

let records = [{"id": 1}, {"id": 2, "date": new Date()}];

return records.sort(function(a: any, b: any) {
      return a.hasOwnProperty('date')
        ? -1
        : b.hasOwnProperty('date')
        ? 1
        : 0;
    });

So I need that all elements with the date were sorted and rest others without date placed on the bottom of the list.

Upvotes: 1

Views: 116

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could check and move the undwanted to bottom by taking a delta of the check.

const
    getISO = d => d instanceof Date
        ? d.toISOString()
        : d;

let records = [{ id: 1 }, { id: 2, date: new Date('2020-01-01') }, { id: 3 }, , { id: 2 }, { id: 4, date: new Date }];

records.sort((a, b) => 
    Number('date' in b) - Number('date' in a) ||
    getISO(b.date || '').localeCompare(getISO(a.date || ''))
);

console.log(records);

Upvotes: 2

Related Questions