js数组去重的方法
在JavaScript中,去重数组是一个常见的操作,有多种方法可以实现,以下是几种常见的方法:
1. 使用 Set 和展开运算符(Spread Operator)
javascript<p>function unique(array) {<p>return [...new Set(array)];<p>}<p>let arr = [1, 2, 2, 3, 4, 4, 5];<p>console.log(unique(arr)); // 输出 [1, 2, 3, 4, 5]<p>
2. 使用 filter() 方法
javascript<p>function unique(array) {<p>return array.filter((item, index, arr) => arr.indexOf(item) === index);<p>}<p>let arr = [1, 2, 2, 3, 4, 4, 5];<p>console.log(unique(arr)); // 输出 [1, 2, 3, 4, 5]<p>
3. 使用 reduce() 和 Set
javascript<p>function unique(array) {<p>return array.reduce((accumulator, current) => {<p> if (!accumulator.includes(current)) {<p>accumulator.push(current);<p> }<p> return accumulator;<p>}, []);<p>}<p>let arr = [1, 2, 4, 2, 4, 6];<p>console.log(unique(arr)); // 输出 [1, 2, 4, 6]<p>
4. 使用 Object 或 Map
javascript<p>function unique(array) {<p>const obj = {};<p>return array.filter(item => {<p> return obj[item] ? false : obj[item] = true;<p>});<p>}<p>let arr = [1, 2, 3, 4, 4, 5, 6, 6, 7];<p>console.log(unique(arr)); // 输出 [1, 2, 3, 4, 5, 6, 7]<p>
5. 使用 for 循环和 splice() 方法
javascript<p>function unique(array) {<p>for (let i = 0; i < array.length; i++) {<p> for (let x = i + 1; x < array.length; x++) {<p>if (array[i] === array[x]) {<p> array.splice(x, 1);<p> x--; // 修正索引<p>}<p> }<p>}<p>return array;<p>}<p>let arr = [1, 2, 3, 4, 1, 2, 3, 4, 2, 1];<p>console.log(unique(arr)); // 输出 [1, 2, 3, 4]<p>
6. 使用 Array.prototype.un 方法(排序后去重)
javascript<p>Array.prototype.un = function() {<p>this.sort();<p>var re = [this];<p>for (var i = 1; i < this.length; i++) {<p> if (this[i] !== re[re.length - 1]) {<p>re.push(this[i]);<p> }<p>}<p>return re;<p>}<p>let arr = [1, 2, 3, 4, 1, 2, 3, 4, 2, 1];<p>console.log(arr.un()); // 输出 [1, 2, 3, 4]<p>
以上方法各有优缺点,选择合适的方法取决于具体的应用场景和性能要求。需要注意的是,对于 NaN 和 undefined 类型,上述方法也能有效去重,因为它们在 Set 中是唯一的。