Click here to Skip to main content
15,886,006 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a beginner in JavaScript and I am trying to solve a task that I came up. I want to write a function that takes in an array like that:
var array = [{date: '02.01.2017'}, {date: '11.11.2016'}, {date: '12.02.2001'}] 
and sorts the array in ascending or descending order depending on the parameter being called with, I have made an attempt, but it doesn't work, how can I create such a function?

What I have tried:

var arr = [{date: '02.01.2017'}, {date: '11.11.2016'}, {date: '12.02.2001'}];

function compare(array, order) {
array.forEach((item) => {
a = item.date.split('.').reverse().join('');
b = item.date.split('.').reverse().join('');

if (order === 'asc') {
if(a > b) {
return 1
}
}
else if(order === 'desc') {
if(a < b) {
return -1
}
}
});
}

compare([{date: '02.01.2017'}, {date: '11.11.2016'}, {date: '12.02.2001'}], 'asc');
Posted
Updated 10-Jun-20 9:46am

Quote:
How to write a function that sorts elements by asc or desc depending on the parameter being called?

My easiest is to use or write a sorting function in ascending order. you will find gazillions of algorithms and source code on internet.
And if desc order is requested, reverse order of sorted array by swapping elements of array.
 
Share this answer
 
The built-in sort method takes a function which is passed two elements from the array and returns a value indicating their relative positions in the sorted list.
Array.prototype.sort() - JavaScript | MDN[^]

You can't pass extra parameters to that function. But you could perhaps use a closure.
Closures - JavaScript | MDN[^]

For example:
JavaScript
function dateComparer(order){
    return function(left, right) {
        var a = left.date.split('.').reverse().join('');
        var b = right.date.split('.').reverse().join('');
        return order === "asc" ? a.localeCompare(b) : b.localeCompare(a);
    };
}

var arr = [ {date: '02.01.2017'}, {date: '11.11.2016'}, {date: '12.02.2001'} ];
arr.sort(dateComparer('desc'));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900