数组,字符串去重

数组去重

方法一:
扩展运算符和 Set 结构相结合,就可以去除数组的重复成员。

// 去除数组的重复成员
[...new Set(array)]

let arr = [3, 5, 2, 2, 5, 5];
let unique = [...new Set(arr)];
// [3, 5, 2]

方法二:
Array.from方法可以将 Set 结构转为数组。

const items = new Set([1, 2, 3, 4, 5]);
const array = Array.from(items);

在这里插入图片描述

这就提供了去除数组重复成员的另一种方法。

function dedupe(array) {
    
    
  return Array.from(new Set(array));
}

dedupe([1, 1, 2, 3]) // [1, 2, 3]

字符串去重

去除字符串里面的重复字符。

[...new Set('ababbc')].join('')
// "abc"

猜你喜欢

转载自blog.csdn.net/weixin_53125679/article/details/124606385