Sandeep Bhatia
Sandeep Bhatia

Reputation: 31

one sort function for different arrays of object in javascript

I want to sort both the array with one comman sort function that can sort by date.

videos = [
    {publishDate: new Date("2016-07-20T07:45:00Z").toISOString()}, 
    {publishDate: new Date("2016-07-27T07:45:00Z").toISOString()}, 
    {publishDate: new Date("2016-07-23T07:45:00Z").toISOString()}
];

persons = [
    {dob: new Date("2016-07-10T07:45:00Z").toISOString()}, 
    {dob: new Date("2016-07-08T07:45:00Z").toISOString()}, 
    {dob: new Date("2016-07-11T07:45:00Z").toISOString()}
];

I can sort with this function byDate()

function byDate(v1, v2) {
    return v1.p > v2.p ? 1 : -1;
}

videos.sort(byDate);

but when I call this function with persons[] array, this gives error because v1.p is not present in persons[] array.

So, I need one sort function that can sort different arrays of objects.

Upvotes: 3

Views: 55

Answers (2)

Nuwan Attanayake
Nuwan Attanayake

Reputation: 1201

simply try,

    videos = [
        {publishDate: new Date("2016-07-20T07:45:00Z").toISOString()}, 
        {publishDate: new Date("2016-07-27T07:45:00Z").toISOString()}, 
        {publishDate: new Date("2016-07-23T07:45:00Z").toISOString()}
    ];
    
    persons = [
        {dob: new Date("2016-07-10T07:45:00Z").toISOString()}, 
        {dob: new Date("2016-07-08T07:45:00Z").toISOString()}, 
        {dob: new Date("2016-07-11T07:45:00Z").toISOString()}
    ];
    
    function byDate(v1, v2) {
        return Object.values(v1) > Object.values(v2) ? 1 : -1;
    }
    
    console.log(videos.sort(byDate));
    console.log(persons.sort(byDate));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You need to specify the key, you like to sort with. This solution takes the key and returns a function for sorting.

function byDate(key) {
    return function (a, b) {
        return a[key].localeCompare(b[key]);
    };
}

var videos = [{ publishDate: new Date("2016-07-20T07:45:00Z").toISOString() }, { publishDate: new Date("2016-07-27T07:45:00Z").toISOString() }, { publishDate: new Date("2016-07-23T07:45:00Z").toISOString() }],
    persons = [{ dob: new Date("2016-07-10T07:45:00Z").toISOString() }, { dob: new Date("2016-07-08T07:45:00Z").toISOString() }, { dob: new Date("2016-07-11T07:45:00Z").toISOString() }];

console.log(videos.sort(byDate('publishDate')));
console.log(persons.sort(byDate('dob')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 5

Related Questions