How to filter an array using two parameters?

Viewed 56

I have a program that adds or removes cars to an array called pile so that the cars can later be selected based on filters and criteria. The code works as it is but I am trying to increase it's efficiency for later changes. Below is code to show what my question is:

if ( var1 == true ) {
  pile.push(car1);
} else if ( var1 == false ) {
  pile = pile.filter( removeCar );
}

function removeCar(elem) {
  return String(elem[0][0]) !== 'Jeep';
}

What I want to do is for removeCar() to have two parameters so it is removeCar(elem, make) such that if make = 'Jeep' the code would function the same way. Unfortunately, as you can see removeCar is called by filter with no parameters and elem is automatically assigned to the current element.

How can I add parameters to the .filter( removeCar)?

4 Answers
pile = pile.filter( x => removeCar(x) );

Try this. If removeCar(x) return true, x(current element of pile) will be added to new pile array

And in your if/else must be '==' or '===' not '='

You can include parameters in the filter if you structure the statement differently: pile = pile.filter( elem => removeCar(elem, make) );

How about this:

if (var1) pile.push(car1);
pile = filterPile(pile, make);

function filterPile(pile, make){
 if(!pile) pile;
 return pile.filter(val=> val[0][0].toString() !== make)
} 

You can define custom filter functions by wrapping the native Array filter() method:

// A custom filter function which accepts a 'pile' and a 'make' parameter.
function removeFromPileByMake(pile, make) {
    // Assuming every element holds an object at [0]
    return pile.filter(elem => elem[0][0] !== make);
}

var make = 'Jeep';

if ( var1 ) {
    pile.push(car1);
} else {
    pile = removeFromPileByMake(pile, make);
}

Related