I couldn’t really figure this out partially because I didn’t know understand why this[i] % 2 was supposed to equal 1. At first I thought it was divided but I guess it’s divisible. Can someone explain this?
Seems 23 is not divisible by 2 so why is it then === 1? (is 1 supposed to measure if it’s true somehow?)
**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 = [];
for (let i = 0; i < this.length; i++) {
if(callback(this[i])) {
newArray.push((this[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 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36.
Challenge: Implement the filter Method on a Prototype
The % (modulus) operator will take a number and divide it with another number as much as possible. It is a ‘Remainder’ operator as MDN says it. What it does is divide a number and return the remainder of it.
Here’s more about it:
So, this code is checking if the item divided by 2 will have a remainder of 1. This is not how it test if it’s divisible by 2 (even number). If you want it to test if it’s an even number, you want to use item % 2 === 0.
This just tests if an integer is even or odd. If 2 goes into item cleanly with no remainder then it is even. In this case item % 2 will return 0 (the remainder). If item is odd then item % 2 will return 1 (because there is a remainder of 1).
So return item % 2 === 1 will return true if the integer is odd and false if it is even.
It doesn’t explain it in detail in the MDN docs I guess because remainders are considered a basic maths concept, so google “remainders” or “modulo operation” for more explanation (note that the JS operator % only acts the same as modulo for positive numbers: -11 % 2 is -1 in JS, but -11 mod 2 is 1).
Yeah with this example it’s simple enough to understand. Maybe it’s just me but if you show 100 people the equation 23 % 2 = 1 then I feel most would be confused since for the majority of our life 23 % 2 equals 11.5. Wouldn’t hurt just to mention remainder in the question but yes I understand / and % are different in code
I see what you are getting at, you are saying that ÷ (the division sign) looks like % (the modulo operator). Understood, but when it comes to programming languages the forward slash is used for division and percent for modulo. It’s just something you’ll have to get used to
Like with myMap, your function myFilter is making a new array. In this case, the function makes a new array that only contains the entries from the old array that return true when passed into the callback function.