qappleh/Interview

第 12题(2019-08-6):编程题,根据以下要求,写一个数组去重函数

qappleh opened this issue · 1 comments

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

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

3.如传入的数组元素为[123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"],则输出:[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]  
// 判断对象
function isObj(obj){
 return Object.prototype.toString.call(obj) === '[object Object]'
}
// 对象重整 对key进行排序
function parseObj(obj){
	let keys = Object.keys(obj).sort()
	let newObj = {}
	for(let key of keys){
               // 不晓得有没有有必要,反正把value为obj的情况也处理一下 - -
                obj[key]=isObj(obj[key])?parseObj(obj[key]):obj[key]
		newObj[key] = obj[key]
	}
	return newObj
}

// 最后
const arr = [1,'1',{a:1,b:"1"},{b:'1',a:1},{a:1,b:2},[1,2,3],null,undefined,undefined]
function passArr(arr){
	return [...new Set(arr.map(item=>
		isObj(item)? JSON.stringify(parseObj(item)) : ( !item ? item : JSON.stringify(item))
    ))].map(item=>!item?item : JSON.parse(item))
}