I've made this function which returns a copy of a given array with no duplicated elements in it.
/**
* Returns an array with only unique elements. Based
* upon an array which might possibly contain duplicates.
* @param { array } arrayToCheck
* @return { array }
* @throws { Error } when given parameter is
* detected invalid.
*/
function createArrayWithoutDuplicates(arrayToCheck) {
'use strict';
var arrayWithoutDuplicates = [];
if (!arrayToCheck || !Array.isArray(arrayToCheck)) {
throw new TypeError('Array expected but ' +
typeof arrayToCheck + ' found.');
}
arrayToCheck.forEach(function(element) {
if (!arrayWithoutDuplicates.includes(element)) {
arrayWithoutDuplicates.push(element);
}
});
return arrayWithoutDuplicates;
}
// --------------------------------------------------
// --------- JUST USAGE-DEMO ------------------------
// -- ... not that important, folks! ;) -------------
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 1, 2, 7, 8];
var arr2 = ['a', 'b', 'c', 'd', 'e', 'a', 'b'];
function testCreateArrayWithoutDuplicates(arrayWithDuplicates) {
let unique = createArrayWithoutDuplicates(arrayWithDuplicates);
console.log('With duplicates: %o', arrayWithDuplicates);
console.log('Without duplicates: %o', unique);
console.log('Array with duplicates: %s', arrayWithDuplicates.length);
console.log('Array without duplicates: %s', unique.length);
}
testCreateArrayWithoutDuplicates(arr);
console.log('\n');
testCreateArrayWithoutDuplicates(arr2);
As far as I can say: It is doing alright.
But I would like to know:
Is there a better pattern for solving the task of getting a duplicate-free array?
If someone knows a better solution then I would appreciate his/her answer.
Moreover:
- Is my documentation understandable and done in a good way? Or do I have to improve?
- Is my parameter validation done correctly?
Looking forward to read your answers. :)
