0

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' ]
1
  • 3
    Native Javascript .filter() or Underscore _.filter() Commented Aug 20, 2014 at 14:22

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.