7

I am trying to output the first two objects in the events array using indexOf.

This doesn't return anything:

var whiteList=['css','js'];

var events =[
    {file: 'css/style.css', type:'css'},
    {file: 'js/app.js', type:'js'},
    {file: 'index/html.html', type:'html'}
];

var fileList= events
    .filter(function(event){
    return event.type.indexOf(whiteList) >- 1 
  })

console.log(fileList);

If I change the function like this, it returns the css and js object, although I expected it to return the html object.

var fileList= events
    .filter(function(event){
    return event.type.indexOf('html') 
  })
OctaviaLo
  • 1,268
  • 2
  • 21
  • 46

2 Answers2

15

You are doing it wrong, it should go like this.

var whiteList = ['css', 'js'];

var events = [{
  file: 'css/style.css',
  type: 'css'
}, {
  file: 'js/app.js',
  type: 'js'
}, {
  file: 'index/html.html',
  type: 'html'
}];

var fileList = events.filter(function(event) {
  return whiteList.indexOf(event.type) > -1
})

console.log(fileList)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
7

With ES6, you could use Set for faster access with larger data sets.

var whiteList = ['css', 'js'],
    whiteSet = new Set(whiteList),
    events = [{ file: 'css/style.css', type: 'css' }, { file: 'js/app.js', type: 'js' }, { file: 'index/html.html', type: 'html' }],
    fileList = events.filter(event => whiteSet.has(event.type));

console.log(fileList);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392