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')
})
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With