【面试题】Js数组去重都有哪些方法?

前端面试题库 (面试必备)            推荐:★★★★★

地址:前端面试题库

 表妹一键制作自己的五星红旗国庆头像,超好看

1. indexOf

  • 定义:
    indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果没有找到匹配的字符串则返回 -1。注意:iindexOf() 方法区分大小写。

  • 语法:
    string.indexOf(searchvalue,start)//;searchvalue必需。searchvalue可选参数。

  • 返回值:
    Number //查找指定字符串第一次出现的位置,如果没找到匹配的字符串则返回 -1。

  • 实例:

//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 数据结构

  • 实例:
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。如果删除失败返回false list.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可有可无,可重复。
  • 写法:
//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},
]
  • 实例:
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');
has map是否有这个键 mymap.has('name');
delete 删除map某个元素 mymap.delete('name');
clear 清空map mymap.clear();
size属性 返回map的成员数量 mymap.size;

4. filter() + indexOf

  • 定义:filter()用于对数组进行过滤。
  • 用法:filter()方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。- 注意: filter() 不会对空数组进行检测;不会改变原始数组。
  • 语法:array.filter(function(currentValue,index,arr){},thisValue);
  • 返回值:返回数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
//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可选。传递给函数的初始值。
  • 实例:
 //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。
  • 实例:
// 判断数组中是否包含某个元素
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函数(升序执行),将其结果汇总为单个返回值
  • 实例:
 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));

边学习边整理,如有问题欢迎指正,大家一起加油!

  前端面试题库 (面试必备)            推荐:★★★★★

地址:前端面试题库

 表妹一键制作自己的五星红旗国庆头像,超好看

猜你喜欢

转载自blog.csdn.net/weixin_42981560/article/details/133141942
今日推荐