Skip to content
Advertisement

How to extend the javascript Array Class?

I am trying to extend the Array class to add a Sum method to it. This is my code below, what am I doing wrong?

Class tipArray extends Array{
    sum(values) {
        for(i in values) {
            total +=i;
        }
    }
}

var testArray = new tipArray();
testArray = [1,2,3,4];
console.log(testArray.sum());

Expected output = 10

Advertisement

Answer

  1. Start by imagining how you would sum an array (maybe something with reduce).
  2. Turn that into a function.
  3. Add that as a method on your class. You can use this to refer to the array.
  4. (optional) ask yourself if you really need a subclass instead of a function that accepts an array.

class tipArray extends Array{
    sum() {
        // Consider making sure the array contains items where sum makes sense here.
        return this.reduce((sum, current) => sum + current)
    }
}

var testArray = new tipArray(1,2,3,4);
console.log(testArray.sum());

// add another element and take another sum
testArray.push(10)
console.log(testArray.sum());
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement