I'm trying to understand javascript's Array.filter
method.
Why is the following code returning undefined
? What am I missing?
function driversWithRevenueOver(driver, revenue) {
driver.filter(function(person) {
if (person.revenue >= revenue) {
return person;
}
});
}
driversWithRevenueOver(
[
{ name: "Sally", revenue: 400 },
{ name: "Annette", revenue: 200 },
{ name: "Jim", revenue: 150 },
{ name: "Sally", revenue: 200 }
],
250
);
It should return:
[{ name: 'Sally', revenue: 400 }]
As per the docs on Array.filter:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
So in your case main issue is that your function does not return anything
even though you have called Array.filter
. So you need to:
function driversWithRevenueOver(driver, revenue) {
return driver.filter(function(person) { // <-- return here
return person.revenue >= revenue)
});
}
More info on the function you pass to the Array.filter
also known as callback:
Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise.
So you need to return a boolean value
from the function.
A shorter version of this filter could simply be:
let data = [{ name: "Sally", revenue: 400 }, { name: "Annette", revenue: 200 }, { name: "Jim", revenue: 150 }, { name: "Sally", revenue: 200 } ]
let result = data.filter(x => x.revenue > 250) // <-- function returns boolean
console.log(result)
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