I am trying to read the filenames of a directory, split the individual filename into an array, then return an array with the index positions and the split filename arrays. Right now it will only read and return one file.
So far, this is what I have:
const splitString = (_str) => {
var myNewString =
_str.split("-");
return myNewString;
} ;
const getInfo = (filePath) => {
let tempfileInfo = [];
let tempfileName;
let tempfileIndex;
fs.readdirSync(filePath).map((i, index) => {
return {
id: tempfileIndex = index + 1;
filename: tempfileName = splitString(i);
}
}); tempfileInfo.push(tempfileIndex, tempfileName);
console.log(tempfileInfo); //returns [20, ['9', 'YE', 'BLU', 'ITEM', '.png']]
}
I have tried adding forEach() to the .map function but that just spits out the same array repeated once then another array with it twice, etc.. until it reaches the end of the files in the directory. Also I don’t think I will actually need the returned index but if for some reason it will help with the rest of my program, I don’t understand why the index is 20 either (yes there are twenty files in the folder and I’m adding 1), the file it is pulling is directly in the center of all of the files and it’s starting the index from the back so what is .map indexing here? It’s probably something simple but for some reason I just cannot see it right now. Thanks in advance for any help!
2
Answers
I solved my own issue. Turns out I did not need to go that deep. This returned the correct array:
You already have a solution inside your code.
Array.map
return a newArray
, you just only have to assign it a variable.