Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript sorting after concat of two arrays now working

I need some help. I’ve used a little function to concat two arrays and remove the duplicates:

let a = ['06.12.2021', '07.12.2021', '19.12.2021', '20.12.2021', '01.03.2022', '03.03.2022', '06.12.2021', '09.01.2022'];
let b = ['17.11.2021', '04.01.2022', '08.01.2022', '09.01.2022'];

let ab = [...new Set( a.concat( b ) )];

console.log(ab);

This works quite nice, but actually they are in a complete bad order. At least, they should start with the lowest date and ends with the highest. I’ve tried a sort function without any success:

let a = ['06.12.2021', '07.12.2021', '19.12.2021', '20.12.2021', '01.03.2022', '03.03.2022', '06.12.2021', '09.01.2022'];
let b = ['17.11.2021', '04.01.2022', '08.01.2022', '09.01.2022'];

let ab = [...new Set(a.concat(b))];

console.log(ab);

ab.sort((a, b) => Date.parse(b) - Date.parse(a));

console.log(ab);

Do you have any advice for me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I added a custom parse function that transforms your date format dd-MM-yyyy to ISO format yyyy-MM-dd. This fixes the date parse issue. I also changed b - a to a - b which sorts in increasing order.

let a = ['06.12.2021', '07.12.2021', '19.12.2021', '20.12.2021', '01.03.2022', '03.03.2022', '06.12.2021', '09.01.2022'];
let b = ['17.11.2021', '04.01.2022', '08.01.2022', '09.01.2022'];

let ab = [...new Set(a.concat(b))];

console.log(ab);

function parse(date) {
    const [d, m, y] = date.split('.');
    return new Date(y, m-1, d);
}

ab.sort((a, b) => parse(a) - parse(b));

console.log(ab);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading