目录
数组对比
[1,2,3] ===[1,2,3] //false
JSON.stringify([1,2,3]) === JSON.stringify([1,2,3]) //true
获取当前元素(含)下所有元素出现次数
<body>
<div id="rich">
<ul>
<li><a>A</a></li>
<li><a>B</a></li>
<li><a>C</a></li>
</ul>
<h3>Hello</h3>
<div>
<input/>
<button></button>
</div>
</div>
</body>
</html>
<script>
let allElement = [document.querySelector('#rich'),...document.querySelector('#rich').getElementsByTagName("*")]
console.log('元素展示:',allElement)
let allNum = [...allElement].reduce((old,news)=>{
let tagName = news.tagName
if(old[tagName]){
old[tagName]++
}else{
old[tagName] = 1
}
return old
},{})
console.log('最终展示:',allNum)
</script>
结果展示
数组去重
//1.使用reduce()方法去重
//注:使用reduce()至少得保证数组有2项才能执行;如果给了初始值,你至少得保证数组有一项才能执行。
let arr = [1, 2, 2, 1, 4, null, null].reduce((accumulator, current) => {
return accumulator.includes(current) ? accumulator : accumulator.concat(current)
}, [])
2,使用new Set()去重
let arr = [...new Set([1, 2, 2, 1, 4, null, null])]
3,多维去重 例如: [1,1,3,4,5,[2,1,12,[22,1,100]],32,[20,12,200]]
function deWeight(list,arrs){
let newList = list.reduce((old,news)=>{
if(!Array.isArray(news)){
if(old.indexOf(news)===-1){
old.push(news)
}
}else{
return deWeight(news,old)
}
return old
},arrs)
return newList
}
deWeight(list,[])
数组降维
//1,多维数组降维flat会更简单,当然flat存在兼容问题:
//(Infinity参数代表无限深度,无参数默认降维一层)
let arr = [0,[1],[2, 3],[4, [5, 6, 7]]].flat(Infinity);// [0, 1, 2, 3, 4, 5, 6, 7]
//2,通过reduce,可以结合concat方法:
let arr = [[1,2],[3,4],[5,6]].reduce((accumulator, current)=>accumulator.concat(current),[]);//[1, 2, 3, 4, 5, 6]
//3,多维数组嵌套,reduce:
let arr = [0,[1],[2, 3],[4, [5, 6, 7]]];
let dimensionReduction = function (arr) {
return arr.reduce((accumulator, current) => {
return accumulator.concat(
Array.isArray(current) ?
dimensionReduction(current) :
current
);
}, []);
}
dimensionReduction(arr); //[0, 1, 2, 3, 4, 5, 6, 7]
获取数组最大数
let arr = [1,2,5,34,34,43,21,8,6]
arr.reduce((old,news)=>{
if(old['max']&&old['max']<news){
old['max'] = news
}else if(!old['max']){
old['max'] = news
}
return old
},{}) //{max:43}
获取数组第二大数
let arr = [1,2,5,34,8,6,34,34,22,22,77,7,66,7,77,66]
arr.reduce((old,news,index,list)=>{
if(index>=2){
if(news>old['max2']){
if(news>=old['max']){
//为了区分存在相同数值,影响第二值的判断
if(news!==old['max'])old['max2'] = old['max']
old['max'] = news
}else{
old['max2']= news
}
}
}else{
if(list[0]>list[1]){
old['max'] = list[0]
old['max2'] = list[0]
}else{
old['max'] = list[1]
old['max2'] = list[0]
}
}
return old
},{}) //{max: 77, max2: 66}
获取数组中每项出现的次数
let arrs = [1,2,3,6,6,5,4,5,6,5,3,2]
arrs.reduce((old,news)=>{
if(old[news]){
old[news]++
}else{
old[news] = 1
}
return old
},{})