Array deduplication
Case 1: The array itself is deduplicated
//数组本身去重
function unique(array) {
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) {
array.splice(j, 1);
j--
}
}
}
}
let array = [1, 5, 2, 3, 6, 3, 2];
unique(array);
console.log('unique', array);//[1, 5, 2, 3, 6]
Case 2: The array itself is not deduplicated
1. Set method
// 1.Set方式
function unique1(array1) {
console.log(new Set(array1))//Set(5) {1, 5, 2, 3, 6}
//(1)方式1
return [...new Set(array1)]
//(2)方式2:Array.from可以创建新的、浅拷贝的数组
return Array.from(new Set(array1))
}
const array1 = [1, 5, 2, 3, 6, 3, 2];
let result1 = unique1(array1);
console.log('unique1', result1);//[1, 5, 2, 3, 6]
2. The way to judge by includes
// 2.通过 includes 判断的方式
function unique2(array2) {
return array2.reduce((accu, cur) => {
if (!accu.includes(cur)) {
accu.push(cur)
}
return accu
}, [])
}
const array2 = [1, 5, 2, 3, 6, 3, 2];
let result2 = unique2(array2);
console.log('unique2', result2);//[1, 5, 2, 3, 6]
3. The way of Object.values
// 3.Object.values(这种方式会直接按照索引进行升序)
function unique3(array3) {
let result = array3.reduce((accu, cur) => {
if (!accu[cur]) {
accu[cur] = cur;
}
return accu
}, {
})
console.log(result);//{1: 1, 2: 2, 3: 3, 5: 5, 6: 6}
//Object.values
return Object.values(result)
}
const array3 = [1, 5, 2, 3, 6, 3, 2];
let result3 = unique3(array3);
console.log('unique3', result3);//[1, 2, 3, 5, 6]
The source address of all front-end interview questions: https://gitee.com/daiwanghao/front-end-interview-questions.git
The above are several methods of different types of array deduplication , please pay attention to the " Front-end Interview Questions " column.
I will share the common problems in my usual projects and the knowledge of the written test and interview with you on CSDN, and make progress together. Come on.