Map/Set to maintain unique array of arrays, Javascript

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

    If you are ok to use a library, try lodash uniqWith. This will recursively find groups of arrays OR objects with the comparator of your choice: equal in your case.

    var arrayofarrays = [ [1,1,2], [1,2,1], [1,1,2], [1,2,1], [2,1,1], [2,1,1] ]
    
    const uniqarray = _.uniqWith(arrayofarrays, _.isEqual);
    
    console.log(uniqarray) //=> [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
    

    Bonus: it works on array of objects too

    var objects = [{ 'x': 1, 'y': {b:1} }, { 'x': 1, 'y': {b:1} }, 
                   { 'x': 2, 'y': {b:1} }, { 'x': 1, 'y': 2 }     ];
    
    const uniqarray = _.uniqWith(objects, _.isEqual);
    
    console.log(uniqarray) 
    // => [{x: 1, y: {b: 1}}, {x: 2, y: {b: 1}}, {x: 1, y: 2}]
    

提交回复
热议问题