What are the methods to remove duplicates from JS arrays?

1. indexOf

  • Definition:
    The indexOf() method returns the first occurrence of a specified string value in a string. If no matching string is found, -1 is returned. Note: i indexOf() method is case sensitive.
  • Syntax:
    string.indexOf(searchvalue,start)//;searchvalue required. searchvalue optional parameter.
  • Return value:
    Number //Find the first occurrence of the specified string. If no matching string is found, -1 is returned.
  • Example:
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()

  • definition:

ES6 provides a new data structure Set. It is similar to an array, but the values ​​of the members are unique and there are no duplicate values. Set itself is a constructor used to generate the Set data structure

  • Example:
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]
  • Other methods of Set object:
method describe Example
add Add a value and return the Set object itself. When adding an element that already exists in the instance, the set will not process the addition. let list = new Set(arr); list.add(5).add(2);//The length of the array is 4 [1,2,3,5]
clear Delete all key/value pairs, no return value list.clear();
delete Delete a key and return the value true. Returns false if deletion fails list.delete(3);
has Returns a Boolean value indicating whether a key is still in the current Set object. list.has(2);
forEach Perform specified operations on each element list.forEach((val,key) => {console.log(key + ‘:’ + val); //1:1 2:2 3 })
keys Perform the specified operation on each element and return the key name for(let key of set.keys()) {console.log(key);}
values Perform the specified operation on each element and return the key value for(let value of set.values()) {console.log(value);}

3. new Map()

  • What is it? :
    The map data structure is a new syntax in es6. Its essence is also a key-value pair, but its keys are not limited to ordinary object strings.
    The data structure of map: a set of structures with key-value pairs. Pay attention to the order of parameters (key: value). The key is unique and the value is dispensable and repeatable.

  • Writing method:

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},
]
  • Example:
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]
  • Other methods of Map objects:
method describe Example
set Add new key value var mymap = new Map(); mymap.set(‘name’,‘Amy’)
get Get the value of a key in the map mymap.get(‘name’);
has Does map have this key? mymap.has(‘name’);
delete Delete an element of map mymap.delete(‘name’);
clear Clear map mymap.clear();
size attribute Returns the number of members of the map mymap.size;

4. filter() + indexOf

  • Definition: filter() is used to filter arrays.
  • Usage: The filter() method creates a new array. The elements in the new array are checked by checking all elements in the specified array that meet the conditions. - Note: filter() does not detect empty arrays; it does not change the original array.
  • grammar:array.filter(function(currentValue,index,arr){},thisValue);
  • Return value: Returns an array containing all elements that meet the conditions. If there are no matching elements, an empty array is returned.
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();
  • Definition and Usage:
    The reduce() method receives a function as an accumulator, and each value in the array (from left to right) is reduced and finally calculated to a value. reduce() can be used as a higher-order function for compose of functions. Note: reduce() will not execute the callback function for empty arrays.
  • grammar:
    array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • Parameters:
    function(total,currentValue, index,arr)required. Function used to execute each array element. Function parameters: total. Required. The initial value, or the return value after the calculation is completed. currentValue is required. The current element. currentIndex optional. The index of the current element. arr is optional. The array object to which the current element belongs.
    initialValueOptional. The initial value passed to the function.
  • Example:
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();
  • Definition and usage:
    The includes() method is used to determine whether a string contains a specified substring. Returns true if a matching string is found, false otherwise. The includes() method is case-sensitive.
  • grammar:
    string.includes(searchvalue,start)
  • Parameters:
    searchvaluerequired. The string to find. startOptional, set the location to start searching from, the default is 0.
  • Return value:
    Boolean value. Returns true if a matching string is found, false otherwise.
  • Example:
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);
③ Remove duplicates
  • reduce This method executes a reducer function you provide (in ascending order) on each element in the array, summarizing its results into a single return value
  • Example:
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));

To learn more about js development, please download the CRMEB open source mall source code to study and study.

Guess you like

Origin blog.csdn.net/CRMEB/article/details/133360325