3

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?

Mystical
  • 2,505
  • 2
  • 24
  • 43

2 Answers2

3

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

joews
  • 29,767
  • 10
  • 79
  • 91
  • 1
    Great! Problem solved (although I am looking forward to shuffle the array in its place later on). – Mystical Oct 20 '16 at 22:37
3

not possible to randomize the array in its place

Wrong.

how do I set 'this' to the variable array 'r' in order to change the array to the new one?

That's impossible in JavaScript. You cannot overwrite an object, not via the this reference and not via a normal variable, you have to actually mutate its properties. If you want to overwrite the variable in which the array reference is stored, you need to explicitly assign to that variable; you cannot do it via a method (since JS does not allow pass-by-reference) and you can only overwrite this reference, not all variables that might contain it.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • **Possible but somewhat unwanted to randomize the array in its place**, and that's because I just wanted to know how it is possible to change the *this* reference which I now realize is impossible because apparently "JS does not allow pass-by-reference." Which is of course, totally fine. Good point though! – Mystical Oct 20 '16 at 23:38