Home > database >  How to sort Array of files naming with DateTime format?
How to sort Array of files naming with DateTime format?

Time:01-09

I fetched an Array of files naming with DateTime format. May I know how I can sort "fetchArray" and made it display like the "expectedArray" below?

    const fetchArray = [
        "root/home/desktop/usr/public/images/09-01-2023_07-17-00.jpg",
        "root/home/desktop/usr/public/images/09-01-2023_07-17-29.jpg",
        "root/home/desktop/usr/public/images/30-11-2022_10-39-29.jpg",
      ];


    expectedArray = [
    "root/home/desktop/usr/public/images/30-11-2022_10-39-29.jpg",
    "root/home/desktop/usr/public/images/09-01-2023_07-17-00.jpg",
    "root/home/desktop/usr/public/images/09-01-2023_07-17-29.jpg",
  ];

CodePudding user response:

Here is how you can sort by filename:

const fetchArray = [ "root/home/desktop/usr/public/images/09-01-2023_07-17-00.jpg", "root/home/desktop/usr/public/images/09-01-2023_07-17-29.jpg", "root/home/desktop/usr/public/images/30-11-2022_10-39-29.jpg", ];

const sortedFiles = fetchArray.reverse((a, b) => {
  let fileANumber = Number(a.split('.jpg')[0]);
  let fileBNumber = Number(b.split('.jpg')[0]);

  return fileANumber = fileBNumber;
});

console.log(sortedFiles)

CodePudding user response:

If you want to sor it by year (It's my conclusion). In that case you should do the following:

  1. If it's "static" path to the file and the name ends with Date, you should try to get the position of year. In that case f.e:

var path = fetchArray[0].slice(42,45)

Then try to play with that directly f.e. in loop.

  1. If you want to sort it in descending order, try to do this:

    expectedArray = fetchArray.sort(); expectedArray.reverse();

You didn't specified question. So my answer is simple as it can be.

  • Related