// 1. indexOf + for循环 var removeDuplicates = function (nums) { let arr = []; for (let i of nums) { if (arr.indexOf(i) === -1) { arr.push(i); } } return arr; };
// 2. 双重for循环 + splice 暴力解决 var removeDuplicates = function (nums) { for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] === nums[j]) { nums.splice(j, 1); j -= 1; // 删除一个数后,应该继续对这个位置新的数判断 } } } return nums; };
// 3. 类似2.,先sort排序,这样只需要一次for循环 var removeDuplicates = function(nums) { if (!Array.isArray(nums)) { console.log('Type Error!'); return ; } else { let arr = nums.sort(); let duplicate_arr = [arr[0]]; for (let i=1;i<arr.length;i++) { if (arr[i] !== arr[i-1]) { duplicate_arr.push(arr[i]); } } return duplicate_arr; } };
// 4. includes 判断一个数组有没有一个值,其实类似于 indexOf var removeDuplicates = function (nums) { let arr = []; for (let i of nums) { if (!arr.includes(i)) { arr.push(i); } } return arr; };
// 5. filter + indexOf var removeDuplicates = function (nums) { return nums.filter((value, index, array) => { return index === array.indexOf(value); }) };
// 6. ES6 Set var removeDuplicates = function(nums) { return Array.from(new Set(nums)) };
测试代码:
let nums = [0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 'hello', 'hello']; console.log(removeDuplicates(nums));
结果:
[ 0, 1, 2, 3, 4, 'hello' ]