编程题

2019-08-03  本文已影响0人  CRJ997

写的灰常长....感觉还需要改,先这样写着

/*
第 113 题:编程题,根据以下要求,写一个数组去重函数(蘑菇街)

如传入的数组元素为[123, "meili", "123", "mogu", 123],则输出:[123, "meili", "123", "mogu"]

如传入的数组元素为[123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"],则输出:[123, [1, 2, 3], [1, "2", 3], "meili"]

如传入的数组元素为[123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"],则输出:[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]
*/
function isSameObject(obj1,obj2){
  if((obj1===null && obj1 === obj2) || (obj1===undefined && obj1 === obj2)) return true;
  else if(obj1 === null || obj2 === null) return false; 
  let length1 = Object.keys(obj1).length;
  let length2 = Object.keys(obj2).length;
  if(length2 !== length1) return false;
  if(length2 === 0 && length2 === length1) return true;
  for(let item in obj1){
    if(obj1[item] instanceof Object && obj2[item] instanceof Object){
        if(!isSameObject(obj1[item],obj2[item])) return false;
    } else {
        if(obj1[item] !== obj2[item]) return false;
    }
  }
  return true;
}

function removeDuplication(array){
    if(array === null || array === undefined) return null;//判空
    if(array && !(array instanceof Array)) return 'need an array';
    if(Array.isArray(array)){
       if(array.some(item=> {//判断有没有对象先
          return item!==null && typeof item ==='object'; 
       })){
        let res = [];
        let middle = [...(new Set(array))];   //去掉非Object的重复值
        for(let i = 0,len = middle.length;i<len;i++){   
         if(!middle[i] || !(middle[i] instanceof Object)){  //null或者其他值直接压入结果数组
            res.push(middle[i]);
            continue;
         } else {       //否则遍历判断对象是否在其他位置有重复值
           let hasd = middle.slice(i+1).some((item,index) => {
            if(!item || !(item instanceof Object)){
                return false;
            } else { //比较i和j位置的对象是否相等
                console.log(middle[i],item);
               return isSameObject(middle[i],item)
            }
           })
           console.log(hasd);
           if(!hasd){
            res.push(middle[i])
           }
         }
        }
        return res;
       } else {
         return [...(new Set(array))]
       }
    }
}
arry1 = [123, "meili", "123", "mogu", 123];
arry2 = [123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"]
array3 = [123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"]
console.log(removeDuplication(array3));
上一篇下一篇

猜你喜欢

热点阅读