当前位置:网站首页>JS 数组去重(含简单数组去重、对象数组去重)
JS 数组去重(含简单数组去重、对象数组去重)
2022-08-01 22:18:00 【朝阳39】
简单数组去重
简单数组:由基础数据类型元素组成的数组,如 [1,‘你好’,true]
方式一 : 利用Set去重
利用 Set 数据结构自动去重的特征实现
let oldList = [1, 2, 3, 3];
let newList = Array.from(new Set(oldList)); // 得到 [1, 2, 3]
类似写法如下:
function arrDistinct(arr){
const newArr = new Set(arr);
return [...newArr]
}
let list = [1,2,2,3,4,4]
console.log(arrDistinct(list))
方式二 : 嵌套循环,自己与自己对比,有重复则删掉
let arr = [1, 2, 3, 2, 2, 1, 3, 4, 2, 5];
//去除数组中重复的数字
for (let i = 0; i < arr.length; i++) {
/*获取当前元素后的所有元素*/
for (let j = i + 1; j < arr.length; j++) {
//判断两个元素的值是否相等
if (arr[i] == arr[j]) {
//如果相等则证明出现了重复的元素,则删除j对应的元素
arr.splice(j, 1);
//当删除了当前j所在的元素以后,后边的元素会自动补位
//使j自减,再比较一次j所在位置的元素
j--;
}
}
}
console.log(arr); // 结果为 [ 1, 2, 3, 4, 5 ]
方式三 : 将不重复的元素放入新数组
//思路:创建一个新数组,循环遍历,只要新数组中有老数组的值,就不用再添加了。
function arrDistinct(array) {
let newArr = [];
for (let i = 0; i < array.length; i++) {
//开闭原则
let bool = true;
//每次都要判断新数组中是否有旧数组中的值。
for (let j = 0; j < newArr.length; j++) {
if (array[i] === newArr[j]) {
bool = false;
}
}
if (bool) {
newArr[newArr.length] = array[i];
}
}
return newArr;
}
let oldList = [1, 2, 3, 4, 5, 2, 3, 4];
let newList = arrDistinct(oldList);
console.log(newList); // 结果 [ 1, 2, 3, 4, 5 ]
方式四 : 使用 lodash 的 uniq()
_.uniq([2, 1, 2]); // => [2, 1]
对象数组去重
对象数组:由对象组成的数组
function arrDistinctByProp(arr,prop){
//只返回第一次出现的,重复出现的过滤掉
return arr.filter(function(item,index,self){
return self.findIndex(el=>el[prop]==item[prop])===index
})
}
let list = [
{
key:'1',
name:'林青霞'
},
{
key:'2',
name:'张三丰'
},
{
key:'1',
name:'段誉'
},
{
key:'1',
name:'段誉'
}
]
//通过name属性去重
console.log(arrDistinctByProp(list,'name'))
另一种可能更容易理解,写法如下:
function soloArray(array, UID) {
let newArr = [];
let UIDlist = [];
array.forEach((item) => {
if (!UIDlist.includes(item[UID])) {
UIDlist.push(item[UID]);
newArr.push(item);
}
});
return newArr;
}
let oldList = [
{
ID: 1,
name: "王小虎",
age: 10,
},
{
ID: 2,
name: "张三",
age: 20,
},
{
ID: 2,
name: "张三",
age: 20,
},
{
ID: 3,
name: "李四",
age: 30,
},
];
let newList = soloArray(oldList, "ID");
console.log(newList);
边栏推荐
- Recycling rental system 100% open source without encryption Mall + recycling + rental
- Error creating bean with name ‘dataSource‘:Unsatisfied dependency expressed through field ‘basicPro
- leetcode 204. Count Primes 计数质数 (Easy)
- Still struggling with reporting tool selection?To take a look at this
- Deep Learning Course2 Week 2 Optimization Algorithms Exercises
- Wechat Gymnasium Reservation Mini Program Graduation Design Finished Work Mini Program Graduation Design Finished Product (2) Mini Program Function
- SAP Spartacus NgExpressEngineDecorator 的工作原理
- LeetCode952三部曲之二:小幅度优化(137ms -> 122ms,超39% -> 超51%)
- 【Verilog刷题篇】硬件工程师从0到入门1|基础语法入门
- 迁移学习——Discriminative Transfer Subspace Learning via Low-Rank and Sparse Representation
猜你喜欢

一种灵活的智能合约协作方式

Kubernetes第零篇:认识kubernetes

毫秒级!千万人脸库快速比对,上亿商品图片检索,背后的极速检索用了什么神器?

Prufer序列

还在纠结报表工具的选型么?来看看这个

复现gallerycms字符长度限制短域名绕过
![[ASM] Bytecode Operation MethodWriter](/img/54/a9f3ddd02ffc02aa965a083c03d322.jpg)
[ASM] Bytecode Operation MethodWriter

Ten years after graduation, financial freedom: those things that are more important than hard work, no one will ever teach you

scikit-learn no moudule named six

如何防范 DAO 中的治理攻击?
随机推荐
xctf攻防世界 Web高手进阶区 webshell
Deep learning Course2 first week Practical aspects of Deep Learning exercises
【建议收藏】ヾ(^▽^*)))全网最全输入输出格式符整理
Flutter基础学习(一)Dart语言入门
Graph Theory - Strongly Connected Component Condensation + Topological Sort
【牛客刷题-SQL大厂面试真题】NO4.出行场景(某滴打车)
论文解读(GSAT)《Interpretable and Generalizable Graph Learning via Stochastic Attention Mechanism》
编曲软件FL studio20.8中文版功能和作用
【C补充】链表专题 - 单向链表
xss相关知识点以及从 XSS Payload 学习浏览器解码
VGUgarbage collector(垃圾回收器)的实现原理
小程序毕设作品之微信体育馆预约小程序毕业设计成品(2)小程序功能
Centos7--MySQL的安装
【开源】Sentinel高性能高可用集群限流解决方案
ImportError: `save_weights` requires h5py. Problem solved
使用分类权重解决数据不平衡的问题
PHP算法之最接近的三数之和
How to add a game character to a UE4 scene
Small application project works WeChat stadium booking applet graduation design of the finished product (1) the development profile
xctf攻防世界 Web高手进阶区 web2