indexof方法_[ 翻译 ] ES6中数组去重的三种方法
原文:How to Remove Array Duplicates in ES6
翻譯:Hytonight云息
有三種方法可以過(guò)濾掉一個(gè)數(shù)組的重復(fù)元素并且返回去重后的新數(shù)組。我最喜歡使用Set,因?yàn)樗罹?jiǎn)。
const array = [' ', 1, 2, ' ',' ', 3]; ? // 1: "Set" [...new Set(array)]; ? // 2: "Filter" array.filter((item, index) => array.indexOf(item) === index); ? // 3: "Reduce" array.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []); ? ? // RESULT: // [' ', 1, 2, 3];1. 使用 Set
set是ES6中引入的新的數(shù)據(jù)類型。set只允許存儲(chǔ)不重復(fù)的值,所以當(dāng)你放入一個(gè)數(shù)組,它會(huì)自動(dòng)去掉重復(fù)的值。
OK,我們回去將代碼分解開(kāi)來(lái)看,其實(shí)就做了兩件事情:
- 首先,我們通過(guò)原數(shù)組array創(chuàng)建了一個(gè)新的set,所有的重復(fù)值都被去除了。
- 然后,我們通過(guò)展開(kāi)運(yùn)算符…轉(zhuǎn)換回了數(shù)組
當(dāng)然,你也可以使用Array.form來(lái)將set轉(zhuǎn)回?cái)?shù)組
const array = [' ', 1, 2, ' ',' ', 3]; ? Array.from(new Set(array)); ? // [' ', 1, 2, 3]2.使用 filter()
為了更好地說(shuō)明這個(gè)方法,我們得先說(shuō)說(shuō)這兩個(gè)方法:indexOf()和filter()。
indexOf
從一個(gè)數(shù)組中返回給定元素第一次出現(xiàn)的索引
const array = [' ', 1, 2, ' ',' ', 3]; ? array.indexOf(' '); // 0 array.indexOf(1); // 1 array.indexOf(2); // 2 array.indexOf(3); // 5filter
filter()方法通過(guò)給定的條件(一個(gè)函數(shù))來(lái)返回一個(gè)新的數(shù)組。換句話說(shuō),如果輪到的這個(gè)元素進(jìn)入了條件函數(shù)后結(jié)果為true,那么它將被加入到過(guò)濾后的新數(shù)組中,反之則不會(huì)加入到結(jié)果數(shù)組中。
const array = [' ', 1, 2, ' ',' ', 3] ? array.filter((item, index) => { ?console.log(// a. Itemitem,// b. Indexindex,// c. indexOfarray.indexOf(item),// d. Conditionarray.indexOf(item) === index,); ?return array.indexOf(item) === index });下面就是執(zhí)行上述代碼后console的輸出。可以看到,重復(fù)的元素就是那些index和indexOf不同的元素。所以,重復(fù)元素返回的結(jié)果就是false。
(譯者按:說(shuō)的再簡(jiǎn)單點(diǎn),就是所有重復(fù)元素只取第一次出現(xiàn)的那個(gè),后來(lái)出現(xiàn)的丟棄)
那如何得到重復(fù)的元素呢?
也是使用filter(),只要將上面的條件反一反就可以啦,如下:
const array = [' ', 1, 2, ' ',' ', 3]; ? array.filter((item, index) => array.indexOf(item) !== index); ? // [' ',' ']3. 使用 reduce()
reduce()方法通過(guò)提供的reducer 函數(shù)來(lái)reduce數(shù)組中的元素并且將他們合并為一個(gè)新的數(shù)組。
(譯者按:難翻,看MDN解釋——reduce() 方法對(duì)數(shù)組中的每個(gè)元素執(zhí)行一個(gè)由您提供的reducer函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個(gè)返回值)
在這個(gè)例子中,我們的reducer函數(shù)用來(lái)檢查最終結(jié)果是否已經(jīng)包含這個(gè)item。如果不包含,那么將它放入最終結(jié)果,如果已經(jīng)包含,則丟棄(或者說(shuō)跳過(guò))這個(gè)item。
reduce常常會(huì)難以理解,所以我們一步步來(lái)看。
const array = [' ', 1, 2, ' ',' ', 3]; ? array.reduce((unique, item) => {console.log(// a. Itemitem,// b. Final Array (Accumulator)unique,// c. Condition (Remember it only get pushed if this returns `false`)unique.includes(item),// d. Reducer Function Resultunique.includes(item) ? unique : [...unique, item],);return unique.includes(item) ? unique : [...unique, item] }, []); // The initial value of our Accumulator is an empty array ? // RESULT: // [' ', 1, 2, 3];console輸出如下:
總結(jié)
以上是生活随笔為你收集整理的indexof方法_[ 翻译 ] ES6中数组去重的三种方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python2和3的编码区别_Pytho
- 下一篇: 字体设置_Endnote教程|字体设置