3 回答

TA貢獻1794條經(jīng)驗 獲得超8個贊
嘗試將內(nèi)部數(shù)組轉(zhuǎn)換為字符串,然后過濾重復(fù)項并再次解析字符串。
let x = [[1, 2], [3, 4], [1, 2]];
var unique = x.map(ar=>JSON.stringify(ar))
.filter((itm, idx, arr) => arr.indexOf(itm) === idx)
.map(str=>JSON.parse(str));
console.log(unique);

TA貢獻1893條經(jīng)驗 獲得超10個贊
過濾器只會導(dǎo)致事情進入 O(n^2)。
當(dāng)前接受的答案使用.filter((itm, idx, arr) => arr.indexOf(itm) === idx)這將導(dǎo)致每次迭代期間每次迭代數(shù)組...n^2。
為什么還要去那里?不僅如此,最后還需要解析。這是很多多余的。
這里沒有真正的好方法來使用過濾器而不達到 O(n^2),所以如果性能是目標(biāo),則可能應(yīng)該避免。
相反,只需使用reduce。它非常簡單且快速輕松地完成 O(n)。
“將集合減少到唯一值?!?/p>
let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
let y = Object.values(x.reduce((p,c) => (p[JSON.stringify(c)] = c,p),{}));
console.log(y);
如果不是很清楚,這里有一個更易讀的 bin 減少版本。
// Sample Data
let dataset = [[1, 2], [3, 4], [1, 2], [2, 1]];
// Create a set of bins by iterating the dataset, which
// is an array of arrays, and structure the bins as
// key: stringified version of the array
// value: actual array
let bins = {};
// Iteration
for(let index = 0; index < dataset.length; index++){
// The current array, from the array of arrays
let currentArray = dataset[index];
// The JSON stringified version of the current array
let stringified = JSON.stringify(currentArray);
// Use the stringified version of the array as the key in the bin,
// and set that key's value as the current array
bins[stringified] = currentArray;
}
// Since the bin keys will be unique, so will their associated values.
// Discard the stringified keys, and only take the set of arrays to
// get the resulting unique set.
let results = Object.values(bins);
console.log(results);
如果您必須走過濾器的路線,則必須使用 n^2。您可以使用 each 迭代每個項目以尋找存在性。
“保留之前沒有重復(fù)的每個元素。”
let x = [
[1, 2],
[3, 4],
[1, 2],
[2, 1]
];
let y = x.filter((lx, li) =>
x.every((rx, ri) =>
rx == lx ||
(JSON.stringify(lx) != JSON.stringify(rx) || li < ri))
);
console.log(y);

TA貢獻1804條經(jīng)驗 獲得超8個贊
好的,字符串哈希的想法很棒。道具到I wrestled a bear once. 我認(rèn)為代碼本身可能會更好一些,所以這是我傾向于做這種事情的方式:
let x = [[1, 2], [3, 4], [1, 2]];
const map = new Map();
x.forEach((item) => map.set(item.join(), item));
console.log(Array.from(map.values()));
如果你想要一個丑陋的內(nèi)襯:
let x = [[1, 2], [3, 4], [1, 2]];
const noRepeats = Array.from((new Map(x.map((item) => [item.join(), item]))).values());
console.log(noRepeats);
添加回答
舉報