[Javascript] Array methods in depth - indexOf
indexOf is used to search for a value or reference inside of an array. In this lesson we first look at what values are returned when a search is successful vs when it's unsuccessful. Then we move onto a technique that shows how to use the return value to create a boolean flag that can be checked easily. We end by filtering 1 array based on the existence of a value in a whitelist array.
var people = ['Wan', 'John', 'Kate', 'Joe']; var indexJoe = people.indexOf('Joe'); var findJoe = people.indexOf('Joe') > -1; console.log(indexJoe, findJoe); //3, true
indexOf can take second params for telling the startLookingIndex:
var people = ['Wan','Joe', 'John', 'Kate']; var indexJoe = people.indexOf('Joe'); var findJoe = people.indexOf('Joe', 2) > -1; console.log(indexJoe, findJoe); //1, false var findJoe = people.indexOf('Joe', 1) > -1; console.log(indexJoe, findJoe); //1, true
Example:
var whitelist = ['.css', '.js']; var events = [ { file: 'css/core.css' }, { file: 'js/app.js' }, { file: 'index.html' } ]; var filtered = events.filter(event => { var ext = event.file.substr(event.file.lastIndexOf('.')); return whitelist.indexOf(ext) > -1; }); console.log(filtered);