数组去重
- set去重
let arr = [1,2,3,4,3,5,4];
let set = new Set(arr);
let newArr = Array.from(set) // Array.from会将类数组或者可遍历对象转为数组
console.log(newArr); //输出结果:1,2,3,4,5
- reduce去重
对象数组中根据某个属性判断是否相同,存在相同的则删除。
let arr = [
{id: 1, a: 10},
{id: 2, a: 11, b: 5},
{id: 1, c: 100},
{id: 3, a: 10},
{id: 2, a: 11, b:90}
]
let obj = {};
let newArr = arr.reduce(function(item, next) {
obj[next.id] ? '' : obj[next.id] = true && item.push(next);
return item;
}, []);
console.log(newArr)
// 输出结果:[{id: 1, a: 10, {id: 2, a: 11, b: 5}, {id: 3, a: 10}]
- map去重
let arr = [ 1, 1, 2, 2, 3, 4, 4, 5, 9, 10, 5 ]
let newArr = []
let map = new Map()
arr.forEach(item => {
map.has(item) ? map.set(item, true) : map.set(item, false)&&newArr.push(item)
});
console.log(newArr) // 输出结果:[1, 2, 3, 4, 5, 9, 10]
- map获取重复
let arr = [ 1, 1, 2, 2, 3, 4, 4, 5, 9, 10, 5 ]
let map = new Map()
arr.forEach(item => {
map.set(item, map.has(item))
});
map.forEach((item, index) => {
item === true ? console.log(index) : null
})
// 输出结果:1,2,4,5
- map获取第一位非重复
let arr = [ 1, 1, 2, 2, 3, 4, 4, 5, 9, 10, 5 ]
function findFirstNoRepeat(arr) {
let map = new Map()
arr.forEach(item => {
map.set(item, map.has(item))
});
for (let [item, index] of map) {
if (index === false) {
return item
}
}
return 'all repeat'
}
findFirstNoRepeat(arr)// return结果: 3
根据选中结果生成布尔数组
let arr = ["A", "B", "C", "D", "E"]
let selectedArr = ["C", "D"]
let boolArr = arr.map(item=>selectedArr.includes(item));
console.log(boolArr) // 返回结果[false, false, true, true, false]
字符串填充
- 字符串前填充
let bankCardNo = '1234567890123456'
let showLast4BankCardNo = bankCardNo.substr(-4).padStart(16,'*')
console.log(showLast4BankCardNo) // 输入结果:············3456
- 字符串后填充
let bankCardNo = '1234567890123456'
let showFront4BankCardNo = bankCardNo.substr(0, 4).padEnd(16,'·')
console.log(showFront4BankCardNo) // 输入结果:1234············
-字符串替换
let bankCardNo = '1234567890123456'
let showFront4BankCardNo = bankCardNo.replace(/(\d{4})\d+(\d{4})$/, "$1 ···· ···· $2")
console.log(showFront4BankCardNo) // 输入结果:1234 ···· ···· 3456
every和some
var ages = [3, 18, 20, 75, 0];
function someTest(age) {
return age.some((item)=>{
return item >= 18;
})
}
function everyTest(age) {
return age.every((item)=>{
return item >= 18;
})
}
console.log(someTest(ages)) // true
console.log(everyTest(ages)) // false
some是任一项为true,则为true
every是每一项为true,才为true
(持续补充ing...)