Map/Set to maintain unique array of arrays, Javascript(Map/Set 维护唯一的数组数组,Javascript)
问题描述
我正在尝试构建唯一的数组数组,这样每当我有新数组要添加时,它应该只在集合中不存在时添加
I am trying to build unique array of arrays such that whenever I have new array to add it should only add if it doesn't already exist in collection
例如存储 [1,1,2] 的所有唯一排列
E.g. store all unique permutations of [1,1,2]
实际:[[1,1,2],[1,2,1],[1,1,2],[1,2,1],[2,1,1],[2,1,1]]
预期:[[1,1,2],[1,2,1],[2,1,1]]
我尝试过的方法:
- Array.Filter:不起作用,因为数组是对象,
uniqueArrComparer中的每个值都是对该数组元素的唯一对象引用.
- Array.Filter: Doesn't work because arrays are object and each value in
uniqueArrCompareris a unique object reference to that array element.
function uniqueArrComparer(value, index, self) {
return self.indexOf(value) === index;
}
result.filter(uniqueArrComparer)
Set/Map:以为我可以构建一个唯一的数组集,但它不起作用,因为 Set 内部使用严格相等比较器 (===),它将考虑每个数组这种情况是独一无二的.
我们无法为 JavaScript Set 自定义对象相等
Set/Map: Thought I can build a unique array set but it doesn't work because Set internally uses strict equality comparer (===), which will consider each array in this case as unique.
We cannot customize object equality for JavaScript Set
将每个数组元素作为字符串存储在 Set/Map/Array 中,并构建一个唯一字符串数组.最后使用唯一字符串数组构建数组数组.这种方法可行,但看起来不是有效的解决方案.
Store each array element as a string in a Set/Map/Array and build an array of unique strings. In the end build array of array using array of unique string. This approach will work but doesn't look like efficient solution.
使用 Set 的工作解决方案
let result = new Set();
// Store [1,1,2] as "1,1,2"
result.add(permutation.toString());
return Array.from(result)
.map(function(permutationStr) {
return permutationStr
.split(",")
.map(function(value) {
return parseInt(value, 10);
});
});
这个问题比任何应用问题都更像是一个学习练习.
This problem is more of a learning exercise than any application problem.
推荐答案
一种方法是将数组转换为 JSON 字符串,然后使用 Set 获取唯一值,然后再次转换回来
One way would be to convert the arrays to JSON strings, then use a Set to get unique values, and convert back again
var arr = [
[1, 1, 2],
[1, 2, 1],
[1, 1, 2],
[1, 2, 1],
[2, 1, 1],
[2, 1, 1]
];
let set = new Set(arr.map(JSON.stringify));
let arr2 = Array.from(set).map(JSON.parse);
console.log(arr2)
这篇关于Map/Set 维护唯一的数组数组,Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Map/Set 维护唯一的数组数组,Javascript
基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
