Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function with .filter() returning undefined instead of filtered array

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 }]
like image 355
jaytix Avatar asked Jun 29 '19 03:06

jaytix


1 Answers

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)
like image 194
Akrion Avatar answered Nov 15 '22 02:11

Akrion