How to implement array deduplication

Method 1: use the splice method to remove duplicate elements

var arr = [7, 1, 'hi', 1, 'hi', true, null, undefined, true, null, undefined]; function normalize (arr) { if (arr && Array.isArray(arr)) { var len = arr.length, map = {}; for (var i = len - 1; i >= 0; i--) { if (arr[i] in map) { arr.splice(i, 1); } else { map[arr[i]] = true; } } return arr; }} console.log(' array deduplicate ', normalize(arr));Copy the code

Method 2: Use the indexOf method

var arr = [7, 1, 'hi', 1, 'hi', true, null, undefined, true, null, undefined]; function normalize (arr) { if (arr && Array.isArray(arr)) { var len = arr.length, res = []; for (var i = 0; i < len; i++) { if (res.indexOf(arr[i]) == -1) { res.push(arr[i]); } } return res; }} console.log(' array deduplicate ', normalize(arr));Copy the code

Method three, skillfully use the extension operator and Set data structure

var arr = [7, 1, 'hi', 1, 'hi', true, null, undefined, true, null, undefined]; function normalize (arr) { if (arr && Array.isArray(arr)) { var res = [...new Set(arr)]; return res; }} console.log(' array deduplicate ', normalize(arr));Copy the code

In method 4, use the new API in ES6 — Array.from() to implement the extended operator functionality in method 3

var arr = [7, 1, 'hi', 1, 'hi', true, null, undefined, true, null, undefined]; function normalize (arr) { if (arr && Array.isArray(arr)) { var res = Array.from(new Set(arr)); return res; }} console.log(' array deduplicate ', normalize(arr));Copy the code