Can anybody tell me what I am missing here? It doesn't give me the expected output.
I wanted to sort the array in ascending and descending order based on the date but for whatever reason, it only sorts the array in descending order.
let res = [
['03-01-2019', 'Test 3'],
['03-01-2020', 'Test 1'],
['03-01-2021', 'Test 2']
];
const toDate = (dateStr) => {
const [month, day, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
let SortedDefault = res; //default array value, no sorting has been done.
let SortedAscDate = res.sort(function (a, b) { return toDate(a[0]) - toDate(b[0]) }); //sort array in asc order
let SortedDescDate = res.sort(function (a, b) { return toDate(b[0]) - toDate(a[0]) }); //sort array in desc order
document.getElementById("default").innerHTML = SortedDefault;
document.getElementById("asc").innerHTML = SortedAscDate;
document.getElementById("desc").innerHTML = SortedDescDate;
<p id="default"></p>
<p id="asc"></p>
<p id="desc"></p>
I was expecting the following results;
03-01-2019,Test 3,03-01-2020,Test 1,03-01-2021,Test 2 //original, no sorting has been done.
03-01-2019,Test 3,03-01-2020,Test 1,03-01-2021,Test 2 //sort in asc order
03-01-2021,Test 2,03-01-2020,Test 1,03-01-2019,Test 3 //sort in des order
Instead, I got this (all three are descending???);
03-01-2021,Test 2,03-01-2020,Test 1,03-01-2019,Test 3 //original, no sorting has been done (but how can it sorted in des order?)
03-01-2021,Test 2,03-01-2020,Test 1,03-01-2019,Test 3 //sort in asc, but it has been sort in desc order
03-01-2021,Test 2,03-01-2020,Test 1,03-01-2019,Test 3 //sort in des order, correct result.
CodePudding user response:
The sort
method sorts the elements of an array in place.
Use res.slice().sort(...)
CodePudding user response:
.sort()
mutates the main array. To overcome you can use a soft copy [...res]
to sort like
let SortedAscDate = [...res].sort(function(a, b) {
return toDate(a[0]) - toDate(b[0])
})
let res = [
['03-01-2019', 'Test 3'],
['03-01-2020', 'Test 1'],
['03-01-2021', 'Test 2']
];
const toDate = (dateStr) => {
const [month, day, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
let SortedDefault = res; //default array value, no sorting has been done.
let SortedAscDate = [...res].sort(function(a, b) {
return toDate(a[0]) - toDate(b[0])
}); //sort array in asc order
let SortedDescDate = [...res].sort(function(a, b) {
return toDate(b[0]) - toDate(a[0])
}); //sort array in desc order
document.getElementById("default").innerHTML = SortedDefault;
document.getElementById("asc").innerHTML = SortedAscDate;
document.getElementById("desc").innerHTML = SortedDescDate;
<p id="default"></p>
<p id="asc"></p>
<p id="desc"></p>