如何过滤掉数组数组中的公共数组

时间:2017-10-10 07:05:19

标签: javascript

我有一个数组数组:

[
  [
    "Serta",
    "Black Friday"
  ],
  [
    "Serta",
    "Black Friday"
  ],
  [
    "Simmons",
    "Black Friday"
  ],
  [
    "Simmons",
    "Black Friday"
  ],
  [
    "Simmons",
    "Black Friday"
  ],
  [
    "Simmons",
    "Black Friday"
  ]
]

我只需要获得唯一的数组,例如:

[
  [
    "Serta",
    "Black Friday"
  ],
  [
    "Simmons",
    "Black Friday"
  ] 
]

我知道对于单个数组元素,我可以使用.filter(),如:

array.filter((d,i)=>array.indexOf(d)==i)

但是我不确定这个案例,没有像lodash这样的库。

1 个答案:

答案 0 :(得分:1)

您可以将一个JSON字符串作为哈希表中数组的键并使用它进行过滤。



var data = [["Serta", "Black Friday"], ["Serta", "Black Friday"], ["Simmons", "Black Friday"], ["Simmons", "Black Friday"], ["Simmons", "Black Friday"], ["Simmons", "Black Friday"]],
    hash = Object.create(null),
    result = data.filter(a => !hash[JSON.stringify(a)] && (hash[JSON.stringify(a)] = true));

console.log(result);