Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of using filter in JavaScript.
/* Filter Example - Object and Numbers*/
const numberList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
const types = [{ name: "Penguin", type: "Bird" }, { name: "Hopper", type: "Rabbit" }, { name: "Duck", type: "Bird" }];
/* Filtering Numbers */
/* ES5 */
const numbersAbove = numberList.filter(function (num) {
return num > 50;
});
/* ES6 */
const numbersAbove2 = numberList.filter((num) => num > 50);
console.log(numbersAbove); // [60, 70, 80, 90, 100]
console.log(numbersAbove2); // [60, 70, 80, 90, 100]
/* Filter Objects - Getting Bird */
const birds = types.filter(function (element) {
return element.type === 'Bird';
});
const birds2 = types.filter((element) => element.type === 'Bird');
console.log(birds); // [{name: 'Penguin', type: 'Bird'}, {name: 'Duck', type: 'Bird'}]
console.log(birds2); // [{name: 'Penguin', type: 'Bird'}, {name: 'Duck', type: 'Bird'}]
console.log(types); //Remains the same as the original
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment