js filter code example

Example 1: js filter array of objects by value

var heroes = [
	{name: “Batman”, franchise: “DC”},
	{name: “Ironman”, franchise: “Marvel”},
	{name: “Thor”, franchise: “Marvel”},
	{name: “Superman”, franchise: “DC”}
];

var marvelHeroes =  heroes.filter(function(hero) {
	return hero.franchise == “Marvel”;
});

// [ {name: “Ironman”, franchise: “Marvel”}, {name: “Thor”, franchise: “Marvel”} ]

Example 2: angular array filter typescript

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

Example 3: filter javascript array

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);

Example 4: .filter js

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

Example 5: how the filter() function works javascript

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const filter = arr.filter((number) => number > 5);
console.log(filter); // [6, 7, 8, 9]

Example 6: js filter

//ES6
let greaterTen = numbers.filter(number => { number > 10 });
console.log(greaterTen); // []

// with return
let greaterTen = numbers.filter(number => number > 10 ); // return implicito
console.log(greaterTen); // [23, 12, 45, 78, 11, 10.1, 84]

// ES5
var greaterTen = numbers.filter(function(){ 
  number > 10 
});
console.log(greaterTen); // []

// with return
var greaterTen = numbers.filter(function(){ 
  return number > 10 
});
console.log(greaterTen);  // [23, 12, 45, 78, 11, 10.1, 84]

Tags:

Css Example