Map/Set to maintain unique array of arrays, Javascript

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

    You can subclass Set for more flexibility in storing objects by storing the result of calling JSON.stringify on added objects.

    class ObjectSet extends Set{
      add(elem){
        return super.add(typeof elem === 'object' ? JSON.stringify(elem) : elem);
      }
      has(elem){
        return super.has(typeof elem === 'object' ? JSON.stringify(elem) : elem);
      }
    }
    let set = new ObjectSet([[1,1,2],[1,2,1],[1,1,2],[1,2,1],[2,1,1],[2,1,1]]);
    console.log([...set]);
    console.log([...set].map(JSON.parse));//get objects back

提交回复
热议问题