Given an array array = [1,5,2,3,4,2,3,1,3,4], you would write a function unique that makes unique(array) [1,5,2,3,4].

1. Method 1: Do not use Set, refer to the principle of counting sort

unique = (array) => { const hash = [] for(let i=0; i<array.length; i++){ hash[array[i]] = true } const result = [] for(let k in hash){ result.push(k) } return result }Copy the code

Disadvantages: This method only supports numeric or string arrays, if the array contains objects, such as array = [{number:1}, 2], error.

Method 2: Use Set

Unique = (array) => {return [...new Set(array)] // return array. from(new Set(array))}Copy the code

Cons: THE API is too new, older browsers don’t support it, and interviewers find it too easy.

3. Map is used, but the API is too new to be supported by older browsers.

unique = (array) => { let map = new Map(); let result = [] for (let i = 0; i < array.length; I ++) {if(map.has(array[I])) {continue} else {// If the key does not exist in the map, Set (array[I], true); result.push(array[i]); } } return result; }Copy the code