The filter() function runs a conditional expression against each entry in an array. If this conditional evaluates to true, the element is added to the output array. If the condition fails, the element is not added to the output array. Because the filter() method returns a new array, you can chain the result with other array methods such as sort() and map(). If you pass the this value, you can reference it by using this keyword inside the callbackfunction.
The this value ultimately observable by callbackFn is determined according to the usual rules for determining the this seen by a function. CallbackFn Function is a predicate, to test each element of the array. Return a value that coerces to true to keep the element, or to false otherwise.
- Otherwise, the value undefined will be used as its this value.
- The item argument is a reference to the current element in the array as filter() checks it against the condition.
- If you pass the this value, you can reference it by using this keyword inside the callbackfunction.
- This callback function accepts one parameter , and then we return a boolean of whether or not that item should be included in the filtered results.
A more natural fit for the latter is to find() the element, rather than filter() a list. Returns a new array with only the elements that passed the test. A common use case of filter() is with an array of objects through their properties. If the current item passes the condition, it gets returned to the new array.
Index The index of the current element being processed in the array. In that repository, there is a worksheet.js file with some sample Star Wars data.
Filtering invalid entries from JSON