返回
巧用JavaScript去重,面试中的必备技能
前端
2023-11-11 06:04:41
JavaScript数组去重是面试中的一个常见问题,因为JS去重可以有多种实现方法,这可以考察面试者对知识的掌握程度。在本文中,我们将介绍几种实现JavaScript数组去重的方法,帮助您在面试中脱颖而出。
方法一:使用Set()方法
Set()方法是ES6中引入的一个新方法,它可以自动去除数组中的重复元素。我们可以使用以下代码实现JavaScript数组去重:
const array = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
方法二:使用filter()方法
filter()方法可以过滤数组中的元素,我们可以使用它来实现JavaScript数组去重。以下代码演示了如何使用filter()方法实现JavaScript数组去重:
const array = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueArray = array.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
方法三:使用indexOf()方法
indexOf()方法可以返回数组中某个元素第一次出现的位置,我们可以使用它来实现JavaScript数组去重。以下代码演示了如何使用indexOf()方法实现JavaScript数组去重:
const array = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueArray = [];
for (let i = 0; i < array.length; i++) {
if (uniqueArray.indexOf(array[i]) === -1) {
uniqueArray.push(array[i]);
}
}
console.log(uniqueArray); // [1, 2, 3, 4, 5]
方法四:使用reduce()方法
reduce()方法可以将数组中的元素聚合为一个值,我们可以使用它来实现JavaScript数组去重。以下代码演示了如何使用reduce()方法实现JavaScript数组去重:
const array = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueArray = array.reduce((accumulator, currentValue) => {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
以上四种方法都是实现JavaScript数组去重的常见方法,您可以在面试中灵活运用这些方法,展现出您的编程能力。