如何使用filter()方法从JavaScript中的数组数组中获取不同的值? [英] How to get distinct values from an array of arrays in JavaScript using the filter() method?
本文介绍了如何使用filter()方法从JavaScript中的数组数组中获取不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数组:
I have an array like this:
let x = [[1, 2], [3, 4], [1, 2], [2, 1]];
我该怎么办才能检索没有重复项的数组?
What should I do to retrieve an array without the duplicates?
[[1, 2], [3, 4], [2, 1]];
我想使用过滤器方法.我试过了,但是没用:
I would like to use the filter method. I tried this but it doesn't work:
x.filter((value,index,self) => (self.indexOf(value) === index))
正如我指定要使用过滤器方法一样,我不认为这个问题是重复的.另外,我得到了几个有趣的答案.
as I specified to use the filter method, I don't think this question is a duplicate. Also, I got several interesting answers.
推荐答案
尝试将内部数组转换为字符串,然后过滤重复对象并再次解析该字符串.
Try converting the inner arrays to a string, then filter the dupes and parse the string again.
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);
这篇关于如何使用filter()方法从JavaScript中的数组数组中获取不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文