methods

Set to heavy

Let arr = [1,1,5,5,7,8,7,8,9,'ture', {},{}] function uniq (arr) {return array. from(new Set(arr))} Console. log(uniq(arr)) // [1, 5, 7, 8, 9, "ture", {...}, {...}Copy the code

For nested for, and then splice deduplicated

Let arr = [1,1,5,5,7,8,7,8,9, 'true', 'true', {}, {}, null, null] function uniq (arr) {for (let I = 0; i<arr.length; i++){ for(let j=i+1; j<arr.length; J++) {if (arr [I] = = = arr [j]) {/ / twice after traversal, if the arr [I] is equal to the arr [j], delete the latter arr. Splice (j, 1); j--; } } } return arr; } console.log(uniq(arr)) // [1, 5, 7, 8, 9, "ture", {...}, {...}, null] If the values are the same, delete the latter valueCopy the code

IndexOf to heavy

Let arr = [1,1,5,5,7,8,7,8,9, 'true', 'true', {}, {}, null, null] function uniq (arr) {if (! Array.isArray(arr)) { console.log('type error! ') return } let array = []; for (let i = 0; i < arr.length; i++) { if (array .indexOf(arr[i]) === -1) { array .push(arr[i]) } } return array; } console.log(uniq(arr)) // [1, 5, 7, 8, 9, "ture", {...}, {...}, null] Check whether the resulting array has the current element, skip if they have the same value, push into the array if they do not.Copy the code

Use the hasOwnProperty of the object to de-weigh

Let arr = [1,1,5,5,7,8,7,8,9, 'true', 'true', {}, {}, null, null] function uniq (arr) {let obj = {}; return arr.filter(function (item, index, arr) { return obj.hasOwnProperty(typeof item + item) ? false : (obj [typeof item + item] = true)})}. The console log (uniq (arr)) / / [1, 5, 7, 8, 9, "true", {...}. // The hasOwnProperty() method of Object returns a Boolean that determines whether the Object contains a particular (non-inherited) property of its own.Copy the code

The Map to heavy

Let arr = [1,1,5,5,7,8,7,8,9, 'true', 'true', {}, {}, null, null] function uniq (arr) {let map = new map (); let array = new Array(); For (let I = 0; i < arr.length; I++) {if (map) from the (arr) [I]) {/ / if you have the key value map. The set (arr [I], true); } else { map.set(arr[i], false); Array.push (arr[I]); } } return array; } the console. The log (uniq (arr)) / / [1, 5, 7, 8, 9, "true", {...}, {...}. // Map is a dictionary data structure provided by ES. Dictionary structures are used to store hash structures that do not duplicate keys. Unlike sets, dictionaries use key-value pairs to store dataCopy the code

This article draws lessons fromhereAs a learning record