Search code examples
javascriptarraysjavascript-objectsreducedom-events

Javascript reduce function doesn't work on this obj


I am new to Javascript and trying to execute below code on parent object but it is not working as expected. Please help.

The below code doesn't work as expected and throws error as:

"TypeError: this.reduce is not a function"

Array.prototype.merge = merge = this.reduce(function(arg1,arg2)   {
    return arg1+arg2;
},[]);

var arrays =  [1,2,3,4,5,6];
console.log(arrays.merge);

It throws error as below:

TypeError: this.reduce is not a function
    at Object.<anonymous> (C:\Program Files\nodejs\merge.js:1:100)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

If I call array directly, it works fine but that is not what I want to do. I should be able to pass array as shown on above example code.

Array.prototype.merge = merge = [1,2,3,4,5,6].reduce(function(arg1,arg2)   {
    return arg1+arg2;
},[]);

console.log(arrays.merge);

Solution

  • This should do the trick!

    Array.prototype.merge = function () {
        return this.reduce(function (arg1, arg2) {return arg1 + arg2;},[]);
    };
    

    By the way, this works because in this case, this is the object that the method is being called on, which is your merge function.