Remove Duplicates from an Array (ES6)


Posted by hoyi-23 on 2021-07-25

方法不適用LeetCode考題,因為會產生新陣列。
leetcode-Remove Duplicates from an Array (ES6)

1. 使用 set()

nums = [0,0,1,2,3,3,4,4,5,6,7,7,];
const newNums = [...new Set(nums)]; 

newNums; //(8) [0, 1, 2, 3, 4, 5, 6, 7]

2. 使用filter搭配indexof

indexOf() 方法會回傳給定元素於陣列中第一個被找到之索引,若不存在於陣列中則回傳 -1。
例如:

const names = ['aa','bb','cc','dd','dd'];

names.indexOf('ee'); // -1
names.indexOf('aa'); // 0
names.indexOf('bb'); // 1
names.indexOf('cc'); // 2
names.indexOf('dd'); // 3

關於 filter : 參考文章


邏輯:
使用filter新增一個陣列,帶入兩個參數進去跑forEach,如果第一個參數的(names)索引 === 第二個參數的(names)索引,那就代表這一個(names)是第一個。就可以把它放入新陣列,其他的就過濾掉。

const nums = [0,0,1,2,3,3,4,4];

nums.filter((item, index) => {
    console.log(
        item, 
        index, 
        nums.indexOf(item), 
        nums.indexOf(item) === index
    );
    return nums.indexOf(item) === index
});

console.log 結果

上面的結果可以看到:
index是每個數值在這個陣列中的索引,而item使用indexOf得出陣列中數值的第一個索引,如果index === indexOf(item) 回傳 true ,就表示 現在這個數值是陣列中的第一個(也就表示不會有重複的!)


3. 使用reduce搭配includes()

includes()方法會判斷陣列是否包含特定的元素,並以此來回傳 true 或 false。
例如:

const names = ['aa','bb','cc'];

names.includes('ee'); // false
names.includes('aa'); // true
names.includes('bb'); // true

關於 reduce : 參考文章


邏輯: 如果當前的值和上一個值是相同的true就不會推入新陣列,若是不同的false(代表與前一個沒有重複),就推入新陣列。

const nums = [0,0,1,2,3,3,4,4];

nums.reduce((acc,current) =>{
    console.log(
        current, //當前值
        acc, //前一個值,若沒有的話可以另外傳入或initialValue。
        acc.includes(current), //這裡會得到 true or false
        acc.includes(current) ? acc : [...acc, current],
    );
    return acc.includes(current) ? acc : [...acc, current],
}, []); //[]是initialValue


#indexOf() #includes() #reduce() #filter() #set()







Related Posts

1338. Reduce Array Size to The Half

1338. Reduce Array Size to The Half

Wampserver如何安裝舊版本php

Wampserver如何安裝舊版本php

執行緒與同步、非同步概念

執行緒與同步、非同步概念


Comments