JavaScript 数组去重方法:3 种常见技巧 - 优化您的代码
"JavaScript 数组去重方法:3 种常见技巧 - 优化您的代码"\n\nJavaScript 中去除数组重复元素是常见任务。本文将介绍三种常用的去重方法,并提供示例代码。\n\n1. 使用 Set 数据结构\n\nSet 数据结构在 ES6 中引入,可以存储任意类型的唯一值。\n\njavascript\nconst array = [1, 2, 3, 4, 4, 5, 5];\nconst uniqueArray = [...new Set(array)];\nconsole.log(uniqueArray); // [1, 2, 3, 4, 5]\n\n\n2. 使用 filter 方法和 indexOf 方法\n\n使用数组的 filter 方法和 indexOf 方法结合,可以创建一个新数组,只包含原数组中的唯一值。\n\njavascript\nconst array = [1, 2, 3, 4, 4, 5, 5];\nconst uniqueArray = array.filter((value, index, self) => {\n return self.indexOf(value) === index;\n});\nconsole.log(uniqueArray); // [1, 2, 3, 4, 5]\n\n\n3. 使用 reduce 方法\n\n使用数组的 reduce 方法可以将一个数组转换为一个值。\n\njavascript\nconst array = [1, 2, 3, 4, 4, 5, 5];\nconst uniqueArray = array.reduce((accumulator, value) => {\n if (accumulator.indexOf(value) === -1) {\n accumulator.push(value);\n }\n return accumulator;\n}, []);\nconsole.log(uniqueArray); // [1, 2, 3, 4, 5]\n\n\n以上是几种常见的方法,可以根据需要选择其中一种方法去重一个数组。\n
原文地址: https://www.cveoy.top/t/topic/pVSr 著作权归作者所有。请勿转载和采集!