Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using indexOf to filter an array

Tags:

javascript

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') 
  })
like image 633
OctaviaLo Avatar asked Oct 10 '16 20:10

OctaviaLo


People also ask

Can you use indexOf for an array?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.

How do you filter data from an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

What is the function of the indexOf () in arrays?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do you find the indexOf of an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.


1 Answers

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)
like image 132
Nenad Vracar Avatar answered Sep 27 '22 23:09

Nenad Vracar