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') 
  })
2
  • 1
    event.type.indexOf('html') returns 0 (the position of the 'h') - 0 is interpreted as false. Commented Oct 10, 2016 at 20:23
  • what do you expect from whatever.indexOf([1,2,3])? Commented Oct 10, 2016 at 20:40

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect, and I was able to use it for another piece of code I was writing. Thanks!
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);

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.