The purpose of this exercise is to create my own Array.prototype.filter() method – myFilter(). On line 2, I add a new myFilter() method, which takes in a function as an argument, to the array object. I loop through each item in the array that called the method, and on line 6 determine if the function has returned anything for that item. If so, I push it to my new output array on line 7.
On line 52, I use the myFilter() method on the “list” array of a few numbers. I call the isTen function, which returns numbers greater than 10. On line 53, I use the myFilter() method on the “arr” array (an array of objects) to call the filterID function which will only return ids that are a valid number. Finally, on line 54, I use the myFilter() method to call the filterFruit function on the fruits array. It returns any fruits with the letter “ap” in the word: apPLE and GRapE.
// create my own filter method
Array.prototype.myFilter = function(func) {
const output=[];
for(let i=0; i<this.length; i++) {
// console.log('this[i]', this[i]);
if(func(this[i])) {
output.push(this[i]);
}
}
return output;
};
function isTen(item) {
if(item >= 10) {
return item
}
};
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
};
function filterID(item) {
if (isNumber(item.id)) {
return item;
};
};
function filterFruit(item) {
let search = 'ap';
if(item.includes(search) === true) {
return item;
}
};
const list = [12, 5, 8, 130, 44];
const arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{ },
{ id: null },
{ id: NaN },
{ id: 'undefined' }
];
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
console.log(list.myFilter(isTen)); // [ 12, 130, 44 ]
console.log(arr.myFilter(filterID));
// [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 } ]
console.log(fruits.myFilter(filterFruit)); // [ 'apple', 'grapes' ]
I took my sample problem data from the MDN Developer Array.prototype.filter() page.