当前位置: 首页 > news >正文

Js数组去重都有哪些方法?

1. indexOf

  • 定义:
    indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果没有找到匹配的字符串则返回 -1。注意:iindexOf() 方法区分大小写。
  • 语法:
    string.indexOf(searchvalue,start)//;searchvalue必需。searchvalue可选参数。
  • 返回值:
    Number //查找指定字符串第一次出现的位置,如果没找到匹配的字符串则返回 -1。
  • 实例:
js
复制代码
//indexOf
var str="Hello world, welcome to the universe.";
var n=str.indexOf("e");
//去重
const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}];
var newArr = [];
arr.forEach((key,index)=>{if(newArr.indexOf(key) === -1){newArr.push(key)}        
})
console.log(newArr);// [1, '1', 17, true, false, 'true', 'a', {}, {}]

2. new Set()

  • 定义:

ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构

  • 实例:
js
复制代码
let arr = [1,1,2,2,3,3];
let set = new Set(arr);
let newArr = Array.form(set);   //Array.from方法可以将Set结构转为数组。
console.log(newArr);   //[1,2,3]
  • Set对象的其他方法:
方法描述实例
add添加某个值,返回Set对象本身,当添加实例中已经存在的元素,set不会进行处理添加let list = new Set(arr); list.add(5).add(2);//数组长度是4 [1,2,3,5]
clear删除所有键/值对,没有返回值list.clear();
delete删除某个键,返回值true。如果删除失败返回falselist.delete(3);
has返回一个布尔值,表示某个键是否还在当前Set对象之中。list.has(2);
forEach对每个元素执行指定操作list.forEach((val,key) => {console.log(key + ‘:’ + val); //1:1 2:2 3 })
keys对每个元素执行指定操作,返回键名for(let key of set.keys()) {console.log(key);}
values对每个元素执行指定操作,返回键值for(let value of set.values()) {console.log(value);}

3. new Map()

  • 是什么?:
    map数据结构是es6中新出的语法,其本质也是键值对,只是其键不局限于普通对象的字符串。
    map的数据结构:一组具有键值对的结构,注意参数顺序(key:value),key具有 唯一性 value可有可无,可重复。

  • 写法:

js
复制代码
//1
var m = new Map([['Lily',12],['Bob',15],['Amy',13]]);
//2
var scoreList = [
{name:'Lily',age:12,score:98},
{name:'Bob',age:15,score:95},
{name:'Amy',age:13,score:99},
]
  • 实例:
js
复制代码
let list = ['你是最棒的2', 8, 8, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, '你是最棒的2',]
let newList3 = [];
let map = new Map();
// 如果map.has指定的item不存在,那么就设置key和value 这个item就是当前map里面不存在的key,把这个item添加到新数组
// 如果下次出现重复的item,那么map.has(item等于ture 取反 !map.has(item)  不执行
list.forEach((item) => {if(!map.has(item)){map.set(item,true)newList3.push(item)}
})
console.log('newList3', newList3);//newList3 (9) ["你是最棒的2", 8, 1, 2, 3, 4, 5, 6, 7]
  • Map对象的其他方法:
方法描述实例
set添加新键值var mymap = new Map(); mymap.set(‘name’,‘Amy’)
get获取map某个键的值mymap.get(‘name’);
hasmap是否有这个键mymap.has(‘name’);
delete删除map某个元素mymap.delete(‘name’);
clear清空mapmymap.clear();
size属性返回map的成员数量mymap.size;

4. filter() + indexOf

  • 定义:filter()用于对数组进行过滤。
  • 用法:filter()方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。- 注意: filter() 不会对空数组进行检测;不会改变原始数组。
  • 语法:array.filter(function(currentValue,index,arr){},thisValue);
  • 返回值:返回数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
js
复制代码
//filter
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 8, 9, 2];
let res = nums.filter((num) => {return num < 5;
});
console.log(res);  // [1, 2, 3, 4, 2]//去重let res = nums.filter((item,index) => {return nums.indexOf(item) === index;
})
console.log(res);  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

5. reduce() + Includes

① reduce();
  • 定义和用法:
    reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。reduce() 可以作为一个高阶函数,用于函数的 compose。注意: reduce() 对于空数组是不会执行回调函数的。
  • 语法:
    array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • 参数:
    function(total,currentValue, index,arr)必需。用于执行每个数组元素的函数。函数的参数:total。必需。初始值, 或者计算结束后的返回值。currentValue必需。当前元素。currentIndex 可选。当前元素的索引。arr可选。当前元素所属的数组对象。
    initialValue可选。传递给函数的初始值。
  • 实例:
js
复制代码//html<button onclick="myFunction()">点我</button> <p>数组元素之和: <span id="demo"></span></p>//js 四舍五入后计算数组元素的总和:var numbers = [15.5, 2.3, 1.1, 4.7];  function getSum(total, num) {return total + Math.round(num);}function myFunction(item) {document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);}
② includes();
  • 定义和用法:
    includes() 方法用于判断字符串是否包含指定的子字符串。如果找到匹配的字符串则返回 true,否则返回 false。includes() 方法区分大小写。
  • 语法:
    string.includes(searchvalue,start)
  • 参数:
    searchvalue必需。要查找的字符串。start可选,设置从哪个位置开始查找,默认为0。
  • 返回值:
    布尔值。如果找到匹配的字符串返回 true,否则返回 false。
  • 实例:
js
复制代码
// 判断数组中是否包含某个元素
var arr = [1, 2, 3, 4, 5];
var result1 = arr.includes(3); // true
var result2 = arr.includes(6); // false
console.log(result1);
console.log(result2);
③ 去重
  • reduce 该方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值
  • 实例:
js
复制代码let arr = [1,3,5,3,5]let newArr = [];let unique = (arr)=>{let newArr = [];//新数组,用来接管不反复的数组for(var i=0; i<arr.length; i++){if(! newArr.includes(arr[i])){newArr.push(arr[i]);}}return newArr;}console.log(unique(arr));

学习更多js开发知识请下载CRMEB开源商城源码研究学习。

http://www.lryc.cn/news/176851.html

相关文章:

  • Vue简单使用
  • 2309C++nlohmann数格示例2
  • 企业沟通平台私有部署,让沟通更高效数据更安全
  • Java流的体系结构(一)
  • 什么是Redux?它的核心概念有哪些?
  • 细胞机器人系统中的群体智能
  • 【办公自动化】用Python将PDF文件转存为图片(文末送书)
  • 不容易解的题9.26
  • 易点易动固定资产管理系统:精准管理与科学采购,降本增效的利器
  • 人大金仓分析型数据库外部表(二)
  • rtp流广播吸顶喇叭网络有源吸顶喇叭
  • Spring学习笔记12 面向切面编程AOP
  • 【0225】源码分析postgres磁盘块(disk block)定义
  • 第九章 动态规划 part11 123. 买卖股票的最佳时机III 188. 买卖股票的最佳时机IV
  • 阿里云服务器共享型和企业级独享有什么区别?
  • Vue.js基本语法上
  • 【1333. 餐厅过滤器】
  • wifi7有关的210个提案
  • 200行C++代码写一个Qt俄罗斯方块小游戏
  • 蓝桥杯每日一题20223.9.26
  • 查看基站后台信息
  • 关于坐标的旋转变换和坐标系的旋转变换
  • 2023.9.19 关于 数据链路层 和 DNS 协议 基本知识
  • 如何保证接口幂等性
  • 搭建智能桥梁,Amazon CodeWhisperer助您轻松编程
  • 数组和指针笔试题解析之【指针】
  • 【Linux】之Centos7卸载KVM虚拟化服务
  • 智能电力运维系统:数字化转型在电力行业的关键应用
  • eslint报错:no-empty-source
  • 图论17(Leetcode864.获取所有钥匙的最短路径)