Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  188] [ 3]  / answers: 1 / hits: 24321  / 8 Years ago, sun, november 13, 2016, 12:00:00

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)


More From » javascript

 Answers
10

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);




[#60078] Thursday, November 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxh

Total Points: 137
Total Questions: 100
Total Answers: 103

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
maxh questions
Tue, May 18, 21, 00:00, 3 Years ago
Mon, Jan 4, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
;