javascript - A rather perverted array deduplication, please find a method! ! !
阿神
阿神 2017-05-19 10:19:12
0
5
586

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]];

阿神
阿神

闭关修行中......

reply all(5)
習慣沉默

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);
巴扎黑

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.

刘奇

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);
给我你的怀抱

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.

淡淡烟草味

new Set()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template