jay*_*tix 4 javascript arrays object
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
);
Run Code Online (Sandbox Code Playgroud)
It should return:
[{ name: 'Sally', revenue: 400 }]
Run Code Online (Sandbox Code Playgroud)
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)
});
}
Run Code Online (Sandbox Code Playgroud)
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:
function driversWithRevenueOver(driver, revenue) {
return driver.filter(function(person) { // <-- return here
return person.revenue >= revenue)
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
95 次 |
最近记录: |