持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情
数组去重
在实际开发当中,数组去重的应用场景很多,当用户需要对数组进行去重操作的时候,我们可以通过请求后端来帮我们进行去重,但是我们也可以直接在前端进行去重。下面我们就介绍几种去重的方法。
Set 去重
Set 去重是最简单的一种,这是 ES6 提供的一种新方法,只能在兼容 ES6 以上的浏览器环境当中使用。Set 是一种新的数据结构,代表集合,它允许你存储任何类型的唯一值,无论是原始值或者是对象引用。因此,根据这个特性,我们可以利用他来进行去重。
/**
* Set去重
*/
function Deduplication(target) {
// 将目标数组存入Set 集合当中
const array = new Set(target);
//直接返回一个Set 的values,将存在set当中的所有值返回出去,变成一个可迭代的对象。
return array.values();
}
console.log(Deduplication([1, 5, 8, 6, 4, 2, 1, 8, 7, 6])); // [Set Iterator] { 1, 5, 8, 6, 4, 2, 7 }
includes 去重
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。我们创建一个新数组,判断target当中的元素是否在result数组当中,如果在,则不添加元素进入,如果不在,则将遍历到的元素加入result数组。
/**
* include 去重
* @param {*} target
*/
function Deduplication(target) {
// 创建目标数组
const result = [];
//循环遍历
for (let i = 0; i < target.length; i++) {
// 通过include来判断当前元素是否在result当中
if (!result.includes(target[i])) {
result.push(target[i]);
}
}
return result;
}
console.log(Deduplication([1, 5, 8, 6, 4, 2, 1, 8, 7, 6])); // [1, 5, 8, 6,4, 2, 7]
indexof 去重
indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
/**
*indexOf 去重
* @param {Array} target
*/
function Deduplication(target) {
const result = [];
for (let i = 0; i < target.length; i++) {
if (result.indexOf(target[i]) == -1) {
result.push(target[i]);
}
}
return result;
}
console.log(Deduplication([1, 5, 8, 6, 4, 2, 1, 8, 7, 6])); // [1, 5, 8, 6,4, 2, 7]