1、对象数组去重:
数组去重:
const a=[{a:1,b:2},{a:2},{a:2},{a:1,c:3},{b:2,a:1}]
结果:[{a:1,b:2},{a:2},{a:1,c:3}]
// 判断两个对象的属性值是否一致
const a = [{ a: 1, b: 2 }, { a: 2 }, { a: 2 }, { a: 1, c: 3 }, { b: 2, a: 1 }]
const isSameObject = (a, b) => {
if (Object.keys(a).length !== Object.keys(b).length) return false;
for (const key in a) {
if (Object.hasOwnProperty.call(a, key)) {
if (a[key] !== b[key]) return false
}
}
return true;
}
const uniqueFn = (tempArr) => {
const res = tempArr.slice(0)
for (let i = 0; i < tempArr.length; i++) {
for (let j = i + 1; j < tempArr.length; j++) {
if (isSameObject(tempArr[i], tempArr[j])) {
console.log(i, j);
res.splice(i, 1)
};
};
};
return res;
}
console.log(uniqueFn(a));
2、事件循环相关
setTimeout(function() {
console.log('setTimeout1'); // 8 setTimeout1
new Promise(function(resolve) {
console.log('promise0'); // 9 promise0
resolve()
}).then(function() {
console.log('settimeout promise resolveed'); // 10 settimeout promise resolveed
})
});
setTimeout(function() {
console.log('setTimeout2'); // 11 setTimeout2
});
const P = new Promise(function(resolve) {
console.log('promise'); // 1 promise
for (var i = 0; i < 10000; i++) {
if(i === 10) {
console.log('for'); // 2 for
}
if (i === 9999) {
resolve('resolve');
}
}
}).then(function(val) {
console.log('resolve1'); // 5 resolve1
}).then(function(val) {
console.log('resolve2'); // 6 resolve2
});
new Promise(function(resolve) {
console.log('promise2'); // 3 promise2
resolve('resolve');
}).then(function(val) {
console.log('resolve3'); // 7 resolve3
})
console.log('console'); // 4 console
3、扁平化数组
实现一个flat函数,把嵌套的数组打平,flat([[1,2,[3,[4,[5]]]]]),返回[1,2,3,4,5]
const flat = (nums) => {
const res = nums.reduce((pre, cur) => {
if (Array.isArray(cur)) {
return [...pre, ...flat(cur)]
} else {
pre.push(cur)
}
return pre
}, [])
return res;
}
console.log(flat([[1, 2, [3, [4, [5]]]]])); // [ 1, 2, 3, 4, 5 ]