I have this array
let arr = [ 'file_1.jpg' , 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db' ]
I want to filter the files that has .jpg and .png on it.
arr.filter() // desired output: [ 'file_1.png','file_2.png' ]
I have this array
let arr = [ 'file_1.jpg' , 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db' ]
I want to filter the files that has .jpg and .png on it.
arr.filter() // desired output: [ 'file_1.png','file_2.png' ]
Filter with a RegExp:
const arr = [ 'file_1.jpg' , 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db' ];
const pattern = /\.(png|jpg)$/; // string should end with .png or .jpg
const result = arr.filter((name) => pattern.test(name));
console.log(result);
const result = arr.filter( link => link.endsWith(".png") || link.endsWith(".jpg"));
The filter function accepts one callback function which returns a boolean for each item of the list.
So you could create a function
that is using a regular expression
to check if a string
is a png
or jpg
.
//
/\./
()
and separate the options using a pipe (|)
: /\.(jpg|png)/
$
at the end: /\.(jpg|png)$/
Then using the test function you can check if a string matches your expression.
arr.filter(isJPEG);
function isJPEG(text) {
return /\.(jpg|png)$/.test(text);
}
var arr = ['file_1.jpg', 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db'];
var filteredList = arr.filter(isJPEG);
console.log(JSON.stringify(filteredList));
function isJPEG(text) {
return /\.(jpg|png)$/.test(text);
}