映射/设置以维护唯一的数组数组,Javascript [英] Map/Set to maintain unique array of arrays, Javascript

查看:92
本文介绍了映射/设置以维护唯一的数组数组,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]]

Actual : [[1,1,2],[1,2,1],[1,1,2],[1,2,1],[2,1,1],[2,1,1]]
Expected : [[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中,并构建一个唯一字符串数组.最后,使用唯一字符串数组构建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)

这篇关于映射/设置以维护唯一的数组数组,Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆