如何使用filter()方法从JavaScript中的数组数组中获取不同的值?

Sno*_*ite 5 javascript arrays

我有一个像这样的数组:

let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
Run Code Online (Sandbox Code Playgroud)

我该怎么办才能检索没有重复项的数组?

[[1, 2], [3, 4], [2, 1]];
Run Code Online (Sandbox Code Playgroud)

我想使用过滤器方法。我试过了,但是没有用:

x.filter((value,index,self) => (self.indexOf(value) === index))
Run Code Online (Sandbox Code Playgroud)

编辑:正如我指定要使用过滤器方法,我不认为这个问题是重复的。另外,我得到了几个有趣的答案。

I w*_*ce. 11

尝试将内部数组转换为字符串,然后过滤重复对象并再次解析该字符串。

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);
Run Code Online (Sandbox Code Playgroud)

  • 简单得多:`Array.from(new Set(arr.map(x => JSON.stringify(x))),x => JSON.parse(x))` (2认同)

Tra*_*s J 7

过滤器只会导致事情进入 O(n^2)。

当前接受的答案使用.filter((itm, idx, arr) => arr.indexOf(itm) === idx)这将导致每次迭代期间每次迭代数组...n^2。

为什么还要去那里?不仅如此,最后还需要解析。这是很多多余的。

这里没有真正的好方法来使用过滤器而不达到 O(n^2),所以如果性能是目标,则可能应该避免。


相反,只需使用reduce。它非常简单且快速轻松地完成 O(n)。

“将集合减少到唯一值。”

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);
Run Code Online (Sandbox Code Playgroud)

如果不是很清楚,这里有一个更易读的 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);
Run Code Online (Sandbox Code Playgroud)


如果您必须走过滤器的路线,则必须使用 n^2。您可以使用 each 迭代每个项目以寻找存在性。

“保留之前没有重复的每个元素。”

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);
Run Code Online (Sandbox Code Playgroud)