Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Created July 12, 2017 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KinoAR/66ae4e507d2b1d0607009c648ec3295d to your computer and use it in GitHub Desktop.
Save KinoAR/66ae4e507d2b1d0607009c648ec3295d to your computer and use it in GitHub Desktop.
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