Map/Set 维护唯一的数组数组,Javascript

Map/Set to maintain unique array of arrays, Javascript(Map/Set 维护唯一的数组数组,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]]

我尝试过的方法:

  1. Array.Filter:不起作用,因为数组是对象,uniqueArrComparer 中的每个值都是对该数组元素的唯一对象引用.
  1. Array.Filter: Doesn't work because arrays are object and each value in uniqueArrComparer is a unique object reference to that array element.

function uniqueArrComparer(value, index, self) {
  return self.indexOf(value) === index;
}

result.filter(uniqueArrComparer)

  1. Set/Map:以为我可以构建一个唯一的数组集,但它不起作用,因为 Set 内部使用严格相等比较器 (===),它将考虑每个数组这种情况是独一无二的.
    我们无法为 JavaScript Set 自定义对象相等

  1. 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

基础教程推荐