'Create new arrays from a list based on a fragment of the filename

Let's say I have the following filelist:

foo-bar_lorem.ext
foo-bar_ipsum.ext
foo-bar_dolor.ext
foo-baz_lorem.ext
foo-baz_ipsum.ext
foo-baz_dolor.ext
foo-amet.ext
foo-sic.ext

What I'd like to do is to create new arrays based on what's between the dash and the underscore, while having an array of a single object when the file has no underscore in it:

The resulting arrays should be as follow:

array1 = ['foo-bar_lorem.ext', 'foo-bar_ipsum.ext', 'foo-bar_dolor.ext'];
array2 = ['foo-baz_lorem.ext', 'foo-baz_ipsum.ext', 'foo-baz_dolor.ext'];
array3 = ['foo-amet.ext'];
array4 = ['foo-sic.ext'];

This is how I'm currently retrieving the filelist using fs:

const path = require('path');
const fs = require('fs');

const myFolder = path.join(__dirname);

fs.readdir(myFolder, function (err, files) {
    
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    //listing all files using forEach
    files.forEach(function (file) {
        console.log(file);
    });
});


Solution 1:[1]

this is the logic need to be made with file object returns from fs.readdir

const files = ['foo-bar_lorem.ext', 'foo-bar_ipsum.ext', 'foo-bar_dolor.ext',
    'foo-baz_lorem.ext', 'foo-baz_ipsum.ext', 'foo-baz_dolor.ext', 'foo-amet.ext', 'foo-sic.ext']




const res = files.reduce((acc, file) => {
    const dir = file.split("-")[1].split("_")[0]
    acc[dir] = [...(acc[dir] ? acc[dir] : []), file]
    return acc;
}, {});



console.log(Object.values(res))

after embedding it inside the callback

function getFiles(myFolder) {
    return new Promise((resolve, reject) => {
        try {
            fs.readdir(myFolder, function (err, files) {
                if (err) {
                    return console.log('Unable to scan directory: ' + err);
                }
                const res = files.reduce((acc, file) => {
                    const dir = file.split("-")[1].split("_")[0]
                    acc[dir] = [...(acc[dir] ? acc[dir] : []), file]
                    return acc;
                }, {});
                resolve(Object.values(res))
            });
        } catch (err) {
            reject(err)
        }
    })
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naor Tedgi