前端数组去重

第一种:数组值去重
let arr = [ "a", "a", "b", "b", "c"] 
let withSet = [...new Set(arr)]
console.log(withSet)
//[ "a", "b", "c"] 
第二种:数组对象去重(TS)
function ArrSet(Arr: any[], id: string): any[] {
        let obj: Object = {}
        const arrays = Arr.reduce((setArr, item) => {
            obj[item[id]] ? '' : (obj[item[id]] = true && setArr.push(item))
            return setArr
        }, [])
        return arrays
 }

let arr = [{name: 'test'}, {name: 'test'},{name: 'test1'}]
console.log(ArrSet(arr, 'name'));
//[{name: 'test'}, {name: 'test1'}]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 Set 和 Map 来实现前端数组去重,具体代码如下:1. 使用 Set: ``` let arr = [1, 2, 2, 4, 5, 4]; let newArr = [...new Set(arr)]; console.log(newArr); // [1, 2, 4, 5] ```2. 使用 Map: ``` let arr = [1, 2, 2, 4, 5, 4]; let map = new Map();for (let item of arr) { if(!map.has(item)) { map.set(item, true); } }let newArr = Array.from(map.keys()); console.log(newArr); // [1, 2, 4, 5] ``` ### 回答2: 前端数组去重的几种方法代码可以有以下几种: 1. 使用Set:将数组转换为Set对象,Set对象会自动过滤重复的元素,然后再将Set对象转换回数组。 ```javascript const uniqueArray = (array) => [...new Set(array)]; ``` 2. 使用filter和indexOf:遍历数组,通过indexOf判断元素在数组中的第一个索引是否等于当前索引,如果相等则表示是唯一的元素。 ```javascript const uniqueArray = (array) => array.filter((item, index) => array.indexOf(item) === index); ``` 3. 使用reduce和includes:遍历数组,通过includes判断是否已经存在相同的元素,如果不存在则添加到结果数组中。 ```javascript const uniqueArray = (array) => array.reduce((result, item) => { if (!result.includes(item)) { result.push(item); } return result; }, []); ``` 4. 使用Map:遍历数组,将元素作为Map的键,判断是否已经存在该键,如果不存在则添加到结果数组中。 ```javascript const uniqueArray = (array) => { const map = new Map(); const result = []; for (const item of array) { if (!map.has(item)) { map.set(item, true); result.push(item); } } return result; }; ``` 以上是几种常见的前端数组去重方法,根据具体的情况选择适用的方法。 ### 回答3: 前端数组去重的几种方法代码如下: 1. 使用Set数据结构去重: ``` let arr = [1, 2, 2, 3, 3, 4, 5, 5]; let newArr = [...new Set(arr)]; console.log(newArr); // [1, 2, 3, 4, 5] ``` 2. 使用filter方法去重: ``` let arr = [1, 2, 2, 3, 3, 4, 5, 5]; let newArr = arr.filter((item, index) => arr.indexOf(item) === index); console.log(newArr); // [1, 2, 3, 4, 5] ``` 3. 使用reduce方法去重: ``` let arr = [1, 2, 2, 3, 3, 4, 5, 5]; let newArr = arr.reduce((prev, curr) => { if (!prev.includes(curr)) { prev.push(curr); } return prev; }, []); console.log(newArr); // [1, 2, 3, 4, 5] ``` 4. 使用Map数据结构去重: ``` let arr = [1, 2, 2, 3, 3, 4, 5, 5]; let newArr = Array.from(new Map(arr.map(item => [item, item])).values()); console.log(newArr); // [1, 2, 3, 4, 5] ``` 这些方法都可以实现数组去重的功能,具体使用哪种方法取决于项目需求和性能要求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值