I have developed a custom method to clean up an array by removing duplicates and sorting it. It was successful and the code looked like this:
// Example array.
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 issue is that I need to call it like this:
names = names.clean_up();
It would be more convenient if I could use it as Array.sort()
for an in-place implementation. How can I achieve that?
names.clean_up();
EDIT: (Seems this belongs here and not in Answers)
The current solution I have implemented feels somewhat inefficient, and I am wondering if there is a better approach.
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 refill.
while (this.length > 0) {
this.pop();
}
set.forEach(function(item){
self.push(item);
});
};
It has been pointed out multiple times that modifying original arrays is not recommended. Why is that?
If a function like Array.sort()
exists, indicating that the language is capable of such operations, why are custom functions discouraged? Why is sort()
acceptable but a custom function is not?