DEV Community

Discussion on: Implementing our own Array.map() method in javascript

Collapse
 
zaky7 profile image
Zakir • Edited
Array.prototype.myFilter = function(callback) {
    const filterArr = [];
    for(let index = 0; index<this.length; index++) {
        if(!!callback(this[index], index, this)) {
            filterArr.push(this[index]);
        }
    }
    return filterArr;
}

Array.prototype.myReduce = function(callback, accumulator) {
    if(this.length < 1) {
        throw new Error("Array is Empty")
    }

    if(!accumulator) {
        if(typeof this[0] === "string") {
            accumulator = '';
        } else if(typeof this[0] === "number") {
            accumulator = 0;
        }
    }

    for(let index=0; index < this.length; index++) {
        accumulator = callback(accumulator, this[index]);
    }
    return accumulator;
}

const names = ['Zakir', 'Rashid', 'Harish'];
const filterNames = names.myFilter(name => name !== 'Zakir');
const statment = names.myReduce((acc, ele) => acc + ele);

console.log(filterNames) // [ 'Rashid', 'Harish' ]
console.log(statment); // Zakir Rashid Harish
Enter fullscreen mode Exit fullscreen mode