I have the following script, which filterfilters duplicates and returnreturns only unique values for an array.
When passing false
or nothing the "original" array is being overwritten, when passing true
a new array is createcreated with unique valuevalues and returned instead.
ScriptThe script should work only with numbers and strings.
I would like to know:
- If it is possible to optimize the code for maximum performance and how,
- If it is possible to improve or write in alternative way logic for
createArray
, maybe a better way in term of code repetition.
https://jsfiddle.net/dj7qxyL7/
Array.prototype.getUnique = function (createArray) {
createArray = createArray === true ? true : false;
var temp = JSON.stringify(this);
temp = JSON.parse(temp);
if (createArray) {
var unique = temp.filter(function (elem, pos) {
return temp.indexOf(elem) == pos;
}.bind(this));
return unique;
}
else {
var unique = this.filter(function (elem, pos) {
return this.indexOf(elem) == pos;
}.bind(this));
this.length = 0;
this.splice(0, 0, unique);
}
}
var duplicates = [0, 0, 1, 1, 2, 3, 1, 1, 0, 4, 4];
console.log('++++ ovveride')
duplicates.getUnique();
console.log(duplicates);
console.log('++++ new array')
var duplicates2 = [0, 0, 1, 1, 2, 3, 1, 1, 0, 4, 4];
var unique = duplicates2.getUnique(true);
console.log(unique);
console.log('++++ original')
console.log(duplicates2);