1. 去重
let a = [2, 3, 4, 5, 4]
let a1 = [2, 3, 4, 5, 4]
// method1 filter并不会改变原来数组
let method1 = a.filter(function (value, index) {
return a.indexOf(value) === index
})
console.log('方法-', method1)
// method2
let method2 = [...new Set(a)]
console.log('方法二', method2)
// method3
let method3 = a.reduce(function (a, b) {
if (a.indexOf(b) == -1) {
a.push(a)
}
return a
}, [])
2. 扁平化数组
let server = require('./server')
server.startServer()
let array = [1, [2, 3, 4, 5, [6, 7, 8, [9, 5, 7, 8], [5, 6, 7]]]]
let c=[];
let resultArray = []
function flatArray (arg) {
for (let i = 0;i < arg.length;i++) {
if (Array.isArray(arg[i])) {
flatArray(arg[i])
}else {
resultArray.push(arg[i])
}
}
}
flatArray(array);
console.log('递归算法', resultArray);
3. 字符出现次数
function collectLetter(s) {
let letterarry = s.split("");
let result = {};
for (let i of letterarry) {
result[i] = (result[i] ||0) +1;
}
for (let j in result) {
console.log(`${j} occures ${result[j]}`);
}
return result;
};
collectLetter("ahdfakjfhkasjfak")
4. 数组的交集以及并集实现
var a=[...new Set([1,2,3]),...new Set([2,3,4])];
console.log("数组并集",a);
var b=[1,2,3].filter(x=>{return [2,3,5,6].indexOf(x)})
console.log("数组交集",b)