惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
月光博客
月光博客
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
U
Unit 42
腾讯CDC
爱范儿
爱范儿
J
Java Code Geeks
有赞技术团队
有赞技术团队
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
B
Blog
Stack Overflow Blog
Stack Overflow Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
小众软件
小众软件
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Y
Y Combinator Blog
大猫的无限游戏
大猫的无限游戏
Microsoft Azure Blog
Microsoft Azure Blog
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - howhy

TypeScript any vs unknown 详细对比 TypeScript interface vs type 完整对比 html 元素包含关系 this 指向 空对象 Object.keys for ...in Reflect.ownKeys ...区别 逻辑运算符和空值运算符 运算符优先级 js 类型显式转换 js 高级函数 js 方法重载 fetch timeout js 任务顺序执行 暂停 js 并发任务 判断两个对象是否相同 js 动态拦截属性 js 通用动画 js groupby js 防抖和节流 实现 instanceof 操作符 js 单例模式 js 继承方法 js new的过程实现 js deepCopy js '=='的隐性类型转换规则
js 数组去重和扁平方法
howhy · 2025-12-26 · via 博客园 - howhy
// 实现多种数组去重方法
const arr = [1, 2, 2, 3, 4, 4, 5, 'a', 'a', 'b'];

// 方法1:使用 Set
console.log([...new Set(arr)])
// 方法2:使用 filter + indexOf

let newArr=arr.filter((item,index)=>{
    return arr.indexOf(item)===index
})
console.log(newArr);
// 方法3:使用 reduce
newArr=arr.reduce((prev,next)=>{
    if(!prev.includes(next)){
        prev.push(next);
    }
    return prev;
},[])
console.log(newArr);
// 方法4:对象属性去重
const newObj={}
arr.map(item=>{
    newObj[item]=item;
})
console.log(Object.values(newObj))
// 实现数组扁平化(多种方法)
const nestedArray = [1, [2, [3, [4]], 5]];

// 期望输出:[1, 2, 3, 4, 5]
    
// 方法1:递归
function arrFlat(arr){
    const newArr=[];
    function flat(arr){
        arr.forEach(element => {
            if(Array.isArray(element)){
                flat(element);
            }else{
                newArr.push(element);
            }
        });
    }
    flat(arr);
    return newArr;
}

console.log(arrFlat(nestedArray))
// 方法2:使用 flat 方法
console.log(nestedArray.flat(4))
// 方法3:使用 reduce
function reduceFlat(arr){
   return arr.reduce((prev, current) => {
    // 核心:如果当前元素是数组,递归扁平化后合并;否则直接添加
    return prev.concat(Array.isArray(current) ? reduceFlat(current) : current);
  }, []); // 初始化累加器为空数组
}
console.log(reduceFlat(nestedArray))
// 方法4:使用扩展运算符