search

Home  >  Q&A  >  body text

javascript - A rather perverted array deduplication, please find a method! ! !

var a = ['hello',{hello: '323651',bye: '43434'},[1,2,34],true,10,9,8,10,'true','hello',true,false,9,{hello: '312312',ok: 32323},[1,2,34]];

阿神阿神2786 days ago567

reply all(5)I'll reply

  • 習慣沉默

    習慣沉默2017-05-19 10:21:12

    For numbers, Boolean types, etc., just add the judgment directly at the end, or add them together. You will understand more clearly when I write it this way.

    var a = ['{"1":1,"2":2}', {1:1, 2:2}, 'hello',{hello: '323651',bye: '43434'},[1,2,34],true,10,9,8,10,'true','hello',true,false,9,'9',{hello: '312312',ok: 32323},[1,2,34]];
    var json = {};
    var arr = [];
    for (let i = 0, len = a.length; i < len; i++) {
      let str = JSON.stringify(a[i]) + typeof a[i];
      if (!json[str]) {
        arr.push(a[i]);
      }
      json[str] = 1;
    }
    console.log(arr);

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:21:12

    Object vs Object and Array vs Array are processed recursively, and other cases are compared directly.

    1. Direct === judgment, if equal, it’s done.

    2. In case of inequality, if it is object vs object or array vs array, compare it with JSON stringify, and everything else will be fine.

    reply
    0
  • 怪我咯

    怪我咯2017-05-19 10:21:12

    If the object is in sequential order or the internal array elements are ordered arrays, then the elements are converted to strings and compared.

    var arr1 =[...],arr2=[....],arr3=[];
    var rst = [];
    var process = function(arr){
        arr.forEach(funciton(v,i){
            var v2s;
            if(v.constructor === Object){
                v2s = JSON.stringify(v);  
            } else if( v.constructor === Boolean){
                v2s = "'"+v.toString()+"'"
            } else {
                v2s = v.toString();
            }
            if (arr3.indexOf(v2s)<0){
                arr3.push(v2s);
                rst.push(v);
            }
        })
    }
    process(arr1);
    process(arr2);
    console.log(rst);

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:21:12

    It is best to use another character to separate the JSONs. If you can only keep it as it is now, use 'hello' to split the array, and then compare to remove duplicates.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:21:12

    new Set()

    reply
    0
  • Cancelreply