方法一:
Array.prototype.distinct = function() { var arr = this, result = [], len = arr.length; arr.forEach(function(value, index, arr) { var bool = arr.indexOf(value, index + 1); if (bool === -1) { result.push(value); } }); return result; } var arr = [1, 1, 2, 3, 3, 3, 4, 2]; console.log(arr.distinct()); // [1, 3, 4, 2]
方法二:利用ES6的Set
function dedupe(arr) { return Array.from(new Set(arr)); } console.log(dedupe(arr)); // [1, 2, 3, 4]
方法三:
function dedupe(arr) { return [...new Set(arr)]; } console.log(dedupe(arr)); // [1, 2, 3, 4]