Search code examples
node.jstypescriptfilterfs

How do I get only the elements from an array that end with "x" or "y"?


I have a function that recursively searches a directory for files and returns them as an array. I only want files that end with ".js" or ".ts". For that, I'm trying to use Array.filter(). However, it looks as if this would not work, since only files ending in ".js" are returned. How can I filter only the files ending in ".js" or ".ts"?

function getFiles(dir: string): string[] {
    let files: string[] = [];
    fs.readdirSync(dir).forEach((file) => {
        if (fs.statSync(path.join(dir, file)).isDirectory()) {
            files = files.concat(getFiles(path.join(dir, file)));
        } else {
            files.push(path.join(dir, file));
        }
    });
    return files;
}

const files = getFiles(path.join(__dirname, "xyz")).filter((file) => file.endsWith(".js" || ".ts"));

Solution

  • ".js" || ".ts" evaluates to .js. Unfortunately you can't pass a condition like this. Try running ".js" || ".ts" in a browser console to see.

    This would be the correct version:

    const files = getFiles(path.join(__dirname, "xyz"))
      .filter(file => file.endsWith(".js") || file.endsWith(".ts"));
    

    Alternatively:

    const files = getFiles(path.join(__dirname, "xyz"))
      .filter(file => file.match(/(j|t)s$/);