Map/Set to maintain unique array of arrays, Javascript

前端 未结 4 1258
星月不相逢
星月不相逢 2020-12-17 18:37

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

E.g. store all un

4条回答
  •  北海茫月
    2020-12-17 19:13

    To get around the problem of each array being a unique object, you can stringify it so it's no longer unique, then map it back to an array later. This should do the trick:

    var arr = [
      [1, 1, 2],
      [1, 2, 1],
      [1, 1, 2],
      [1, 2, 1],
      [2, 1, 1],
      [2, 1, 1]
    ];
    
    
    var unique = arr.map(cur => JSON.stringify(cur))
      .filter(function(curr, index, self) {
        return self.indexOf(curr) == index;
      })
      .map(cur => JSON.parse(cur))
    
    console.log(unique);
    

提交回复
热议问题