Functional programming JS - 1

Javascript array filter and reject example

by sendil J

HTML

<textarea readonly id="result" style="min-height:200px;"> </textarea>

JavaScript

var animals =[
	{name: 'sam', species: 'dog'},
	{name: 'ruby', species: 'cat'},
	{name: 'gem', species: 'fish'},
	{name: 'kong', species: 'monkey'},
	{name: 'jammy', species: 'dog'},
	{name: 'king', species: 'lion'}
]
var arr = [];
var isDog = function(animal){
	
  if(animal.species === 'dog'){
  	arr.push(animal)
    return arr
  }
  
}

var dogs = animals.filter(isDog);
var otherAnimals = _.reject(animals, isDog); // to use underscore you have add framework Underscore 1x

var output = document.getElementById('result') ;
output.innerHTML = dogs[0].name +' '+ dogs[0].species;
output.innerHTML +='\n\nOther animals - '
//alert(otherAnimals.length);
otherAnimals.forEach(function(obj){
	//console.log(i);
	output.innerHTML +='\n'+ obj.name +' '+ obj.species;
})
console.log(arr)