Reputation: 10696
Below is much simplified logic I am working on, I want to find files with matching location (folder) in a array.
I was able to get this working using vanilla JS loop, can you suggest better/easier/underscore-like way to achieve such functionality?
// source
var arr = [
"file:/anotherName/image1.jpg",
"file:/anotherName/image2.jpg",
"file:/anotherName/image3.jpg",
"file:/folderName/image4.jpg",
"file:/folderName/image1.jpg",
"file:/folderName/image2.jpg",
"file:/folderName/image3.jpg",
"file:/folderName/image4.jpg"
];
// array to store matches
var tmp = [];
for (var i = 0; i < arr.length; i++) {
if( arr[i].indexOf('file:/folderName/') !== -1) tmp.push(arr[i]);
};
console.log(tmp);
// [ 'file:/folderName/image4.jpg',
// 'file:/folderName/image1.jpg',
// 'file:/folderName/image2.jpg',
// 'file:/folderName/image3.jpg',
// 'file:/folderName/image4.jpg' ]
Upvotes: 0
Views: 48
Reputation: 1243
You can use filter. I'd also use a regex match
var arr = [
"file:/anotherName/image1.jpg",
"file:/anotherName/image2.jpg",
"file:/anotherName/image3.jpg",
"file:/folderName/image4.jpg",
"file:/folderName/image1.jpg",
"file:/folderName/image2.jpg",
"file:/folderName/image3.jpg",
"file:/folderName/image4.jpg"
];
var tmp = _.filter(arr, function (el) {
return el.match(/file:\/folderName/);
});
console.log(tmp);
Upvotes: 2