我有一個重復的陣列。我正在尋找一種省略重復值的方法,即
[['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']]
變成
[['cream'], ['cake'], ['cheese'], ['bread'], ['butter']]
任何干凈的方法來做到這一點?
uj5u.com熱心網友回復:
console.log(Object.keys([
['cream'],
['cake'],
['cheese'],
['bread'],
['cream'],
['cake'],
['cheese'],
['bread'],
['butter']
].reduce((acc, val) => { // map to object
acc[val] = true
return acc;
}, {})).map(key => [key])) // map object back to array
uj5u.com熱心網友回復:
- 定義一個
Set來存盤陣列元素 - 使用
Array#reduce,遍歷串列。在每次迭代中,通過使用 連接其元素將當前陣列轉換為字串Array#join。然后,如果該值不在集合中,則添加它并將當前陣列推送到累積串列中。
const arr = [['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']];
const set = new Set();
const res = arr.reduce((list, e) => {
const val = e.join();
if(!set.has(val)) {
set.add(val);
list.push(e);
}
return list;
}, []);
console.log(res);
uj5u.com熱心網友回復:
這里有一個班輪:
const data = [['cream'], ['cake'], ['cheese'], ['bread'], ['cream'], ['cake'], ['cheese'], ['bread'], ['butter']];
console.log([...new Set(data.flat())].map(i => [i]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390705.html
標籤:javascript 数组
