The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Check if a Value is in an Array with indexOf

Check if a Value is in an Array with indexOf

5:21
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.
Watch this lesson now
Avatar
egghead.io

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.

Avatar
Simona

Hi! just wandering what are those 'require' and 'extaname' methods that are used inside 'filtered' variable. I've searched through the web and didn't find it. Paste the code into one js file of mine and, as I expected, console logged me with 'require is undefined'.
So it is not a standar javascript method?
Thank you!

In reply to egghead.io
Avatar
Robert

Simona,

require is a way to pull in modules (code) from another file. The term is "Common JS".
http://stackoverflow.com/questions/9901082/what-is-this-javascript-require

extaname is specific to node.js I believe.

If you're just writing javascript, the code would be:

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);
In reply to Simona
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?