Map/Set to maintain unique array of arrays, Javascript

前端 未结 4 1260
星月不相逢
星月不相逢 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:21

    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)

提交回复
热议问题