WEB_UI WEB_UI - 1 month ago 5
Javascript Question

JavaScript array.prototype how to set 'this' to a new array obtained by a method

I've attempted to define a randomize method to

Array.prototype
like so :


Array.prototype.randomize = function() { // Yes, this method does cause the array to have 'holes', but its good enough for this example/demonstration
var r = new Array(this.length); // Possible but somewhat unwanted to randomize the array in its place, therefore it has to be set to this new array later on.

this.forEach(function(e) {
r[Math.floor(Math.random() * r.length)] = e;
});

// how do I set 'this' to the variable r? (In order to change the array to the new and randomized array 'r')
return r;

}


This method does return the randomized array, but how do I change the array itself as well?

Answer

As the comments say, changing an array in place in place is a better way to shuffle.

But if you did need to replace all of the elements in one go, you could use Array#splice:

Array.prototype.randomize = function() { 
    var r = /* the algorithm to get a replacement array... */;

    this.splice(0, r.length, ...r);
    return this;
}

... is the spread operator. It's part of ES2015.

Spread operator compatibility table