JavaScript function to create a duplicate-free copy of an array 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. :)
Sets are basically like magic for pulling unique values from an array; since, by their very definition, any Set will only hold one copy of any specific value, no matter how many times you try to add it.

That, combined with the ability of Sets to be easily turned back into arrays using the spread operator, makes the overall task rather straight-forward:

function noDuplicates(arr){
  return [...new Set(arr)]
}


It actually makes the task so quick and easy that it begs the question of whether a function is even needed; since anytime you need to pull only the unique values of an array you can simply use:

var unique = [...new Set(arr)] 


Both the function-based and non-function-based approaches are fully viable options though, so choose whichever you prefer.  Hope this was helpful!