Iladarsda
Iladarsda

Reputation: 10696

Underscore - search in array for matching paths

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

Answers (1)

Josh Bodah
Josh Bodah

Reputation: 1243

You can use filter. I'd also use a regex match

http://jsfiddle.net/x5j3600z/

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

Related Questions