host_255 host_255 - 25 days ago 10
Javascript Question

Array.prototype.reject(): TypeError: ....reject is not a function

I am taking a cool online course about functional programming in JavaScript. I was following along just fine until the instructor used the

Array.prototype.reject()
and it did not work for me at run time.

I would like to use "reject" instead of a for loop because it is less code. But, my browser, NodeJS and Express Code consoles tell me that
reject is not a function
.

I researched other articles that discuss
promise.reject
is not a function, but provide solutions that do not make sense to my scenario.

Here is the example code in the course:

var animals = [
{ name: 'Fluffykins', species: 'rabbit' },
{ name: 'Caro', species: 'dog' },
{ name: 'Hamilton', species: 'dog' },
{ name: 'Harold', species: 'fish' },
{ name: 'Ursula', species: 'cat' },
{ name: 'Jimmy', species: 'fish' }
];


var isDog = function(animal){
return animal.species === 'dog';
}

var otherAnimals = animals.reject(isDog);


The work-around with a for-loop:

var notDogs = animals.filter(function(animal){
return animal.species !== 'dog';
});


Its output is:

> notDogs
[ { name: 'Fluffykins', species: 'rabbit' },
{ name: 'Harold', species: 'fish' },
{ name: 'Ursula', species: 'cat' },
{ name: 'Jimmy', species: 'fish' } ]


Please help me use Array.prototype.reject().

EditL

I found Array.prototype.reject() at GitHub/Array.prototype.reject)

Answer

Array.prototype.reject isn't a thing unless a library/custom code adds the reject method to Arrays.

To achieve what you want, you should use the Array.prototype.filter method like you already are. I'm not sure what you think is longer about it because you can write it the same way:

var animals = [
  { name: 'Fluffykins', species: 'rabbit' }, 
  { name: 'Caro', species: 'dog' }, 
  { name: 'Jimmy', species: 'fish' }
];

function noDogs(animal) {
  return animal.species !== 'dog';
}

var otherAnimals = animals.filter(noDogs);
console.log(otherAnimals);