Reputation: 317
Hope this is won't take much time, thank you in advance.
so i want to achieve something like this but i don't know how
let arr = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
let newArray = [];
for(let i = 0; i < this.length; i++){
if(callback(param) === ){ // I want only the filtered items to get pushed to the newArray
newArray.push(callback(this[i]))
}
}
return newArray;
};
var new_arr = arr.myFilter(function(item) {
return item % 2 === 1;
});
Upvotes: 0
Views: 116
Reputation: 1795
Can try this
let arr = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
let filteredArray = [];
for(let i = 0; i < this.length; i++){
const currentElement = this[i];
if(callback(currentElement)) {
filteredArray.push(currentElement);
}
}
return filteredArray;
};
var new_arr = arr.myFilter(function(item) {
return item % 2 === 1;
});
console.log(new_arr);
Upvotes: 1
Reputation: 48600
Change your conditional to this:
if (callback(this[i])) {
newArray.push(this[i]);
}
You need to evaluate the current item i.e. this[i]
by passing it to the callback
to evaluate the condition as true
, in order to push
the current item to the newArray
.
let arr = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
let newArray = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i])) {
newArray.push(this[i]);
}
}
return newArray;
};
var newArr = arr.myFilter(function(item) {
return item % 2 === 1; // is odd
});
console.log(newArr); // [23, 65, 5];
If you are interested, there is a polyfill for Array.prototype.filter()
hosted over at MDN.
if (!Array.prototype.myFilter) {
Array.prototype.myFilter = function(func, thisArg) {
'use strict';
if (!((typeof func === 'Function' || typeof func === 'function') && this)) {
throw new TypeError();
}
var len = this.length >>> 0,
res = new Array(len), // preallocate array
t = this,
c = 0,
i = -1;
var kValue;
if (thisArg === undefined) {
while (++i !== len) {
// checks to see if the key was set
if (i in this) {
kValue = t[i]; // in case t is changed in callback
if (func(t[i], i, t)) {
res[c++] = kValue;
}
}
}
} else {
while (++i !== len) {
// checks to see if the key was set
if (i in this) {
kValue = t[i];
if (func.call(thisArg, t[i], i, t)) {
res[c++] = kValue;
}
}
}
}
res.length = c; // shrink down array to proper size
return res;
};
}
let arr = [23, 65, 98, 5];
var newArr = arr.myFilter(function(item) {
return item % 2 === 1; // is odd
});
console.log(newArr); // [23, 65, 5];
Upvotes: 1