1

I'm curious how to go about implementing my own sort function on the Array object. Ignoring all the usual warnings/dangers about extending/overriding a built-in, consider this:

Array.prototype.sort = function() {
    this = mySortFunction(this);
    function mySortFunction(arr) { ... };
};

Inside the closure, this refers to the Array object [number, number2, number3, etc.]. How do I go about reassigning this to be the result of my internal sorting function? Is it possible?

2
  • 1
    I would like to be able to call someArray.sort() and not someArray = someArray.sort() Commented Dec 30, 2013 at 12:50
  • The native sort method mutates the array, you could make use of it. But I'd say don't do mutation, it's dangerous, counter-intuitive and can be the source of silly bugs, IMO. Commented Dec 30, 2013 at 13:05

1 Answer 1

1

Your solution seems a little redundant:

Array.prototype.sort = function() {
    this = mySortFunction(this);
    function mySortFunction(arr) {
        arr = yetAnotherSortFunction(arr)
        function yetAnotherSortFunction(arr2) {...}
        // and so on...
    };
};

If you really want to do it this way, why not reference your array directly in the first place:

Array.prototype.sort = function() {
    // your implementation:
    // for (var i = this.length, ...
    //     if (this[0] == ...
    //         this[i] = ...
    // ...
};
Sign up to request clarification or add additional context in comments.

2 Comments

Aha, I'm not sure why I didn't think of that. Early morning I guess? This makes things a bit trickier because I'm implementing a merge sort consisting of divide(arr) and merge(left, right). After I have the result of calling var sorted = divide(this), is there a clever way to update the this array to equal the new, sorted array?
To me, it feels wrong to do this, there must be a better way. However, you could have a look at this: stackoverflow.com/a/456996/2060966

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.