Created
July 12, 2017 20:09
-
-
Save KinoAR/66ae4e507d2b1d0607009c648ec3295d to your computer and use it in GitHub Desktop.
An example of using filter in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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