Ad

Overwrite The This Value In Array.prototype

- 1 answer

I've found that the native js sort function screws up from time to time so I wanted to implement my own. Lets say i have the following :

Array.prototype.customSort = function(sortFunction, updated) {...}
var array = [5, 2, 3, 6]
array.customSort(function(a,b) {return a - b})
console.log(array)

Array should be [2, 3, 5, 6]

Updated is the array that has been sorted.

No matter what I return in customSort, the order of array is still in the original order. How do I overwrite the 'this' value / get it to point to the array with the correct order?

Ad

Answer

I just ended up iterating over the updated array and replacing each value in this with the value in updated. In code, that looks like...

function customSort(cb) {
    ...//updated is the sorted array that has been built
    var that = this;
    _.each(updated, function (ele, index) {
        that[index] = ele;
    })
}

I wanted the function to operate in the exact same way the native array.sort function does - it overwrites the array provided instead of returning a new, sorted array.

I find it odd that this works... you cannot overwrite the entire this value in one clean sweep but you can in steps. I couldn't do this for in the customSort function :

this = updated;
Ad
source: stackoverflow.com
Ad