I have to filter a prototype without using the .filter
method.
I thought that I had it, but it gave me a mistake in one of the tests, I checked the answer, but I don't fully understand it and when i searched for it, my answer is the only one that appears.
Write your own
Array.prototype.myFilter()
, which should behave exactly likeArray.prototype.filter()
. You should not use the built-in filter method. The Array instance can be accessed in themyFilter
method usingthis
.
This is the Prop:
Array.prototype.myFilter = function(callback) {
const newArray = [];
// Only change code below this line
// Only change code above this line
return newArray;
};
This is the answer they need:
for(let i = 0; i < this.length; i++){
if(Boolean(callback(this[i], i, this)) === true){
newArray.push(this[i])
}
}
This is the answer i came up with:
for(let i = 0; i < this.length; i++){
if(callback(this[i]){
newArray.push(this[i])
}
}
This are the Tests:
Passed:[23, 65, 98, 5, 13].myFilter(item => item % 2) should equal [23, 65, 5, 13].
Passed:["naomi", "quincy", "camperbot"].myFilter(element => element === "naomi") should return ["naomi"].
Failed:[1, 1, 2, 5, 2].myFilter((element, index, array) => array.indexOf(element) === index) should return [1, 2, 5].
Passed:Your code should not use the filter method.`
I don't understand this part
(this[i], i, this)
The callback for Array#filter
accepts three arguments:
element
the current elementindex
the index of the elementarray
the array being iterated onWhat is asked of you is to make myFilter
behave exactly like filter
. Therefore you cannot omit these arguments when calling the user's predicate:
for(let i = 0; i < this.length; i++){
if(callback(this[i], i, this)){
newArray.push(this[i])
}
}