Help Wanted: filter method on a prototype

Could someone help me a bit to understand the step by step of this please, whats actually filtering ? and whats the step by step process ?

Your code so far


// The global variable
var s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback){
// Only change code below this line
var newArray = [];
this.forEach(function(i) 
{if (callback(i)==true) 
newArray.push(i)
}
)
// Only change code above this line
return newArray;

};

var new_s = s.myFilter(function(item){
return item % 2 === 1;
});

console.log(new_s)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.

Challenge: Implement the filter Method on a Prototype

Link to the challenge:

It explains about the Array.prototype.filter() method in the previous lesson.

The filter method on arrays allows you to create a new array made up of all elements from the original array that return a truthy value from a callback function.

// function that returns true when passed a positive number
const isPositive = x => x > 0;
// an array of numbers
const numbers = [-5, 4, -3, 2, -1, 0];
// Creates a new array of all positive numbers in `numbers`.
// This will pass each element from `numbers` to `isPositive`
// in order. If `isPositive` returns true, then the element is
// added to the new array assigned to `positives`.
const positives = numbers.filter(isPositive);

console.log(positives); // [4, 2]

i understand the filter method, the thing here is to make a filter without using the filter method, and im kinda lost on how this is working and whats actually the filtering condition

The filtering condition is the truthiness of the return value from callback.

1 Like

so, the actual condition is this function

(function(item){
return item % 2 === 1;
})

i guess is trying to filter odds from even (coz i saw the results) but not sure how x % 2===1 works hahah, something like if it can be divided by 2, i see it like if x % 2 is equal to 1

I was confused, I thought your question was about implementing a filter clone, but it was actually about the remainder operator %.

It returns the remainder from division. So as you surmised:

const isOdd = num => num % 2 === 1;
const isEven = num => num % 2 === 0;
1 Like

I was confused about it too, because i couldnt find the condition or atleast didnt make much sense to me. Thanks you very much for the help :smiley: