Array and object methods & array de duplication

Time:2021-12-4
What are the native methods of JavaScript arrays and objects?
Array:
  • arr.concat(arr1, arr2, arrn);–Merge two or more arrays. This methodcan’tModify the original array, but return a new array
  • arr.fill(value,start,end) ;–Fills all elements in an array from the start index to the end index with a fixed value. This methodmeetingModify the original array
  • arr.filter((element,index,array)=>{},this) ;–The filter method filters the array and returns a new array that holds all elements that pass the test of the provided function.This methodcan’tModify the original array
  • arr.reduce((previousValue,currentValue,index,array) => {},initialValue);–The reduce method iterates over all items of the array, also known as “accumulator”, and returns a value finally calculated by the function.
  • arr.join(",");–Returns a string that concatenates all elements of an array.can’tModify the original array
  • arr.sort();–Sorts the elements of the array and returns the array.This methodmeetingModify the original array
  • arr.unshift(e1, e2, en);–Adds an element to the head of an array and returns the new length of the array. This methodmeetingModify the original array
  • arr.push(e1, e2, en);–Adds an element to the end of an array and returns the new length of the array. This methodmeetingModify the original array
  • arr.pop();–Delete the elements at the end of the array. This methodmeetingModify the original array
  • arr.shift();Delete the element of the array header. This methodmeetingModify the original array
  • arr.splice(index, count);–Method to delete elements anywhere. This methodmeetingModify the original array
  • arr.reverse();–Inverts the position of the elements in the array and returns the array. This methodmeetingModify the original array
  • arr.slice(start, end);–A segment of the intercepted array without the end of the packet header and returns a new array.can’tModify the original array
  • arr.splice(index, count, e1, e2, en);–Add elements anywhere in the array. This methodmeetingModify the original array
  • arr.indexOf(searchElement,fromIndex);–Returns an array in which a given element can be foundFirst index, if it does not exist, – 1 is returned.
  • arr.includes(searchElement,fromIndex);//ES6 — judge whether an array contains a specified value, and return a Boolean value according to the situation.
  • arr.map((currentValue,index,array) => {} ,this);–Create a new array. The result is that each element in the array is the return value after calling the provided function once.This methodmeetingModify the original array
  • arr.forEach((currentValue,index,array) => {} ,this);–Executes the given function once for each element of the array.
  • arr.from(arrayLike,(currentValue) => {} ,this);–Create a new array from a similar array or iteratable object, shallow copy of the array instance.This methodmeetingModify the original array
  • arr.find((element,index,array) => {} ,this);–Returns the data in the array that satisfies the provided test functionValue of the first element。 Otherwise returnundefinedThe find method does not change the array
  • arr.findIndex((element,index,array) => {} ,this);–Returns the data in the array that satisfies the provided test functionIndex of the first element。 If no corresponding element is found, – 1 is returned.FindIndex does not modify the called array
  • arr.flat(depth);–The array will be traversed recursively according to a specified depth, and all elements and the elements in the traversed sub array will be combined into a new array to return.This methodcan’tModify the original array
  • arr.flatMap((currentValue,index,array) => {} ,this);–First, use the mapping function to map each element, and then compress the result into a new array. The flat with a depth value of 1 is almost the same as the map, butflatMapUsually the efficiency of merging into one method is slightly higher. This methodcan’tModify the original array
  • arr.some((element,index,array)=>{},this)–According to the judgment conditions, whether one of the elements of the array is satisfied. If one is satisfied, true is returned
  • arr.every((element,index,array)=>{},this)–According to the judgment conditions, whether the elements of the array are all satisfied. If so, true is returned
Object:
  • Object.assign();–Assigns the values of all enumerable properties from one or more source objects to the target object, which willReturn target object
  • Object.defineProperty() ;–Define a new property directly on an object, or modify an existing property of an object and return the object
  • object.hasOwnProperty(prop);–Whether the object has the specified attribute in its own attribute (return Boolean value)
  • Object.getOwnPropertyNames();–Returns an array of property names for all of the specified object’s own properties
  • object.propertyIsEnumerable(prop);–Determines whether the specified property is enumerable (returns a Boolean value)
  • object.valueOf();–Returns the original value of the specified object
  • object.toString();–Returns a string representing the object,Object.prototype.toString.call()
  • Object.create();–Create a new object and use the existing object to provide the information of the newly created objectproto
  • Class.prototype.isPropertyOf(object);–Tests whether one object exists on the prototype chain of another object
  • Object.keys() ;–Method returns an array of its own enumerable properties for a given object
  • Object.values();–Method returns an array of all enumerable property values of a given object itself
  • Object.entries();–Method returns an array of key value pairs of enumerable properties of a given object
  • Object.setPrototypeOf() ;–Method to prototype a specified object
  • Object.getPrototypeOf() ;–Method returns the prototype of the specified object
What is the difference between array. Splice() and array. Splice()?

Arr.slice (start position (including), end position (excluding)):“Read” the elements specified in the array, and the original array will not be modified;
arr.splice(index, count, [insert Elements]):Operation “on the element specified in the array will modify the original array and return the deleted element;
index :Is the starting position of the operation
count = 0 :Insert element,count > 0 :Delete element;
[insert Elements] :Insert a new element into the array;

Summary of array de duplication methods:
  • Method 1: use ES6 set to remove duplicate (the most commonly used in ES6)
//Set de duplication in ES6
function unique(array) {
   return Array.from(new Set(array));
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
 //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}]
//{} no weight removal
  • Method 2: use for to nest for, and then split to remove duplication (the most commonly used in Es5)
//Double layer for loop
function unique(arr) {
   let len = arr.length;
   //Double layer loop, outer loop element, inner loop value comparison. If the values are the same, delete the value.
    for (let i=0; i<len; i++) {
        for (let j=i+1; j<len; j++) {
            if (arr[i] == arr[j]) {
                arr.splice(j, 1);
                //Splice will change the length of the array, so subtract the length len and subscript j by one
                len--;
                j--;
            }
        }
    }
    return arr;
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
// [1, "true", 15, false, undefined, NaN, NaN, "NaN", "a", Object {  }, Object {  }]
//Nan and {} did not remove the weight, and the two nulls disappeared directly
  • Method 3. Use indexof to remove duplicate
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array = [];
    for (var i = 0; i < arr.length; i++) {
        if (array .indexOf(arr[i]) === -1) {
            array .push(arr[i])
        }
    }
    return array;
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
   // [1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {…}, {…}]        
   //Nan, {} did not remove the weight
  • Method 4. Using sort ()
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return;
    }
    arr = arr.sort()
    var arrry= [arr[0]];
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] !== arr[i-1]) {
            arrry.push(arr[i]);
        }
    }
    return arrry;
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
//[0, 1, 15, NaN, NaN, "NaN", {…}, {…}, "a", false, null, "true", true, undefined] 
//Nan, {} did not remove the weight
  • Method 5. De duplication by using the characteristics that the attributes of the object cannot be the same
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var arrry= [];
     var  obj = {};
    for (var i = 0; i < arr.length; i++) { 
        if (!obj[arr[i]]) {
            arrry.push(arr[i])
            obj[arr[i]] = 1
        } else {
            obj[arr[i]]++
        }
    }
    return arrry;
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
//[1, "true", 15, false, undefined, null, NaN, 0, "a",  {...}] 
//// the two trues are directly removed, and Nan and {} are de duplicated
  • Method 6. Use includes
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array =[];
    for(var i = 0; i < arr.length; i++) {
            If (! Array. Includes (arr [i])) {// includes detects whether the array has a value
                    array.push(arr[i]);
              }
    }
    return array
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
 //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}, {…}]     
//{} no weight removal
  • Method 7: use hasownproperty
function unique(arr) {
    var obj = {};
    return arr.filter(function(item, index, arr){
        return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
    })
}
    var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
        console.log(unique(arr))
//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}]  
//Everything's gone
  • Method 8. Using filter
function unique(arr) {
  return arr.filter(function(item, index, arr) {
    //Current element, the first index in the original array = = the current index value, otherwise the current element is returned
    return arr.indexOf(item, 0) === index;
  });
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
//[1, "true", true, 15, false, undefined, null, "NaN", 0, "a", {…}, {…}]
//{} no weight removal
  • Method 9. Use recursive de duplication
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array =[];
    for(var i = 0; i < arr.length; i++) {
            If (! Array. Includes (arr [i])) {// includes detects whether the array has a value
                    array.push(arr[i]);
              }
    }
    return array
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
 //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}, {…}]     
//{} no weight removal
  • Method 10. Using map data structure to remove duplication
function unique(arr) {
    let map = new Map();
        let array = new Array();  //  Arrays are used to return results
        for (let i = 0; i < arr.length; i++) {
            If (map. Has (arr [i]) {// if the key value exists
            map .set(arr[i], true);
        } else {
            map .set(arr[i], false);   //  If there is no key value
            array .push(arr[i]);
        }
    }
    return array ;
}
 var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
    console.log(unique(arr))
//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a",  {...}, {...}]
//{} no weight removal
  • Method 11. Use reduce + includes
function unique(arr){
    return arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[]);
}
var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr));
// [1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {…}, {…}]
  • Method 12 [… New set (ARR)]
[...new Set(arr)]
//There is so little code (in fact, strictly speaking, it is not a method, but only simplifies the code compared with the first method)
Quickly disorder an array
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function(){
    return Math.random() - 0.5;
})
console.log(arr);
Determine whether it is an array
  • Array.isArray(arr)
  • Object.prototype.toString.call(arr) === '[Object Array]'
  • arr instanceof Array
  • array.constructor === Array

reference resources:Latest array de duplication

Recommended Today

The real problem of Alibaba IOS algorithm can’t hang up this time

More and more IOS developers continue to enter the peak of job hopping in 2020 Three main trends of interview in 2020: IOS bottom layer, algorithm, data structure and audio and video development Occupied the main battlefield. Data structure and algorithm interview, especially figure, has become the main reason for the failure of most first-line […]