I have created a custom prototype with which to clean up an array so as to remove duplicates and sort it. It worked and looked like this:
// given an example array such as this.
var names = [ 'Lara', 'Lucy', 'Alexa', 'Vanessa', 'Lucy', 'Brianna', 'Sandra' ];
Array.prototype.clean_up = function(){
var
set = []
;
this.forEach(function(item){
if ( set.indexOf(item) === -1 ) {
set.push(item);
}
});
set.sort();
return set;
};
My only gripe is that I have to call it like this:
names = names.clean_up();
I would prefer it if I could call it as followed, like Array.sort()
(I believe this is called an in-place implementation). How could you do that?
names.clean_up();
EDIT: (Apparently, this belongs here and not in Answers)
My current solution looks as follows, but it feels a bit ineffective. I wonder if it could be done better.
Array.prototype.clean_up = function(){
var
set = [],
self = this
;
this.forEach(function(item){
if ( set.indexOf(item) === -1 ) {
set.push(item);
}
});
set.sort();
// reset and re-fill.
while (this.length > 0) {
this.pop();
}
set.forEach(function(item){
self.push(item);
});
};
Ineffective for one, and for the other: it has been mentioned several times that you should not modify original arrays. Why is that?
I mean, if there is a function like Array.sort()
then it shows, that the language is capable of doing it, and that some implementations seem to be "okay"? Why is sort()
okay but a custom function not?