js之数组和字符串去重的几种方法

1、数组去重

1.1 reduce方法

const arr = [1, 2, 3, 4, 3, 2, 1];
const newArr = arr.reduce((pre, cur) => {
    
    
	!pre.includes(cur) && pre.push(cur);
	return pre;
}, [])

console.log(newArr); // [1, 2, 3, 4]

1.2 Set方法1

const arr = [1, 2, 3, 4, 3, 2, 1];
const newArr = [...new Set(arr)];

console.log(newArr); // [1, 2, 3, 4]

1.3 Set方法2

const arr = [1, 2, 3, 4, 3, 2, 1];
const newArr = Array.from(new Set(arr));

console.log(newArr); // [1, 2, 3, 4]

2、去除字符串里面的重复字符

const str = 'asdfdsa';
const newStr = [...new Set(str)].join('');

console.log(newStr); // 'asdf'

猜你喜欢

转载自blog.csdn.net/qq_42667613/article/details/122299553