This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
66. remove duplicates from an array

There are different approaches to remove duplicates from an array in JavaScript, each with their own time and space complexity:

  1. Using Set: Convert the array to a Set object, then convert back to an array. This approach has a time complexity of O(n), as it iterates over the array only once, and a space complexity of O(n) for storing the Set object.
function deduplicate(arr) {
  arr = [...new Set(arr)];
  return arr;
}
  1. Using filter() method: Filter out the elements that occur more than once in the array. This approach has a time complexity of O(n^2), as it has to search for duplicates in the array for each element in the array, and a space complexity of O(1).
function deduplicate(arr) {
  arr = arr.filter((element, index) => arr.indexOf(element) === index);
  return arr;
}
  1. Using reduce() method: Use a reduce function to create a new array with unique elements only. This approach has a time complexity of O(n), as it iterates over the array only once, and a space complexity of O(n) for storing the new array.
function deduplicate(arr) {
  arr = arr.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);
  return arr;
}

Overall, the approach that uses a Set object has the best time and space complexity, with a time complexity of O(n) and a space complexity of O(n).