[Javascript Basics] Array methods and their applications

Check if it is an array

  • instanceof operator, which can determine whether an object belongs to a certain type

  • Array.isArray() is used to determine whether an object is an array, isArray() is a method provided in HTML5

    var arr = [1, 23]; 
    var obj = {}; 
    console.log(arr instanceof Array); // true 
    console.log(obj instanceof Array); // false 
    console.log(Array.isArray(arr));   // true 
    console.log(Array.isArray(obj));   // false 
    

add/remove

  • push arr.push(element1, ..., elementN)
    Function: Append an item to the end of the array
    Parameter: The specific item to be added, which can be one item or multiple items
    Return value: the length of the new array
    Whether to change the original array: change

    var ary=['a','b','c'];
    var res= ary .push ('d','e')
    console.log(ary);//['a','b','c','d','e'];
    console.log(res);//5
    
  • pop:
    Function: delete the last item of the array
    Parameters: none
    Return value: deleted item
    Whether to change the original array: change

    var ary = ['1','2','3'];
    var res = ary.pop();
    console.log(ary); // ['1','2'];
    console.log(res); // ['3'];
    
  • unshift arr.unshift(element1, ..., elementN)
    Role: add content to the beginning of the array
    Parameters: the element or elements to add to the beginning of the array
    Return value: the length of the new array
    Whether to change the original array: change

    var ary = ['a','b','c'];
    var res = ary.unshift('d','e');
    console.log(ary); //['d','e','a','b','c'];
    console.log(res); // 5
    
  • shift
    Function: delete the first item of the array
    Parameters: none
    Return value: deleted item
    Whether to change the original array: change

    var ary = ['a','b','c'];
    var res = ary.shift();
    console.log(ary); // ['b','c'];
    console.log(res); // ['a'];
    
  • splice:
    Function: delete/add/modify
    Parameters: splice(n,m,...x); complete writing, the first parameter represents starting from the n index, delete m items, and replace the deleted content with x
    Return value: is an array with each item deleted
    Whether to change the original array: yes

    // add feature
    var ary = [1,2,3,4,5];
    var res = ary.splice(1,0,6,7);
    console.log(ary); // [1,6,7,2,3,4,5];
    console.log(res); // [], delete 0 items, the return value is an empty array
    
    // delete function
    var ary = [1,2,3,4,5];
    var res = ary.splice(1,2);
    console.log(ary); // [1,4,5];
    console.log(res); // [2,3]
    
    //Modify function
    var ary = [1,2,3,4,5];
    var res = ary.splice(1,2,6,7);
    console.log(ary); // [1,6,7,4,5];
    console.log(res); // [2,3}
    

take specific content

  • slice:
    Role: select specific content from the original array
    Parameters: slice(n, m): Select from index n (including n) - index m item (excluding m)

    • If the parameter is negative, it means to extract from the penultimate element in the original array, slice(-2) means to extract the penultimate element in the original array to the last element (including the last element)

    Return value: The return value is an array, and each item returned is a copied item
    Whether to change the original array: no change

    var ary = [1,2,3,4,5];
    var res = ary.slice(1,3);
    var res2 = ary.slice(-3,-1)
    console.log(ary); // [1,2,3,4,5];
    console.log(res); // [2,3];
    console.log(res2) // [3,4];
    

concatenated array

  • concat
    Function: realize the splicing of multiple arrays or values
    Parameters: array or value
    Return value: The return value is the new array after concatenation
    Whether to change the original array: no change
    var ary = [1,2,3,4,5];
    var res = ary.concat(6,7);
    var res2 = ary.concat(6,[7,8]);
    var res3 = ary.concat(6,[7,[8,9]]);
    var res4 = ary.concat();
    console.log(ary); // [1,2,3,4,5];
    console.log(res); // [1,2,3,4,5,6,7];
    console.log(res2); //[1,2,3,4,5,6,7,8];
    console.log(res3) // [1,2,3,4,5,6,7,[8,9]];
    // concat() If the argument to the operation is an array, then the elements in the array are added, not the array.  If it is a two-dimensional (or more) array, concat can only 'unpack' one layer of the array
    console.log(res4) // [1,2,3,4,5];
    //If concat() has no parameters or the parameter is an empty array, the purpose of cloning the array can also be achieved
    

convert to string

  • toString:
    Role: can convert a logical value to a string
    Parameters: none
    Return value: The return value is the converted string
    Whether to change the original array: no change

    var ary1=[1,2,3];
    var res=ary1.toString();===>"1,2,3"
    
  • join:
    Function: Convert the array to a string through the specified connector
    Parameters: Connector
    Return value: The return value is the converted string
    Whether to change the original array: no change

    var ary = [1,2,3,4,5];
    var res = ary.join('-');
    console.log(ary); // [1,2,3,4,5]
    console.log(res); // "1-2-3-4-5"
    

sort

  • reverse reverse order
    Function: reverse the array
    Parameters: none
    Return value: The return value is the new sorted array
    Whether to change the original array: change

    var ary = [1,2,3,4,5];
    var res = ary.reverse();
    console.log(ary); //[[5,4,3,2,1]
    console.log(res); // [5,4,3,2,1]
    
  • sort sort
    Function: sort the array
    Parameters: None or a function
    Return value: the new sorted array
    Whether to change the original array: change

    var ary = [1,5,7,9,12,24,56,87,92];
    var ary2 = [1,5,7,9,12,24,56,87,92];
    var ary3 = [1,5,7,9,12,24,56,87,92];
    var res = ary.sort();
    var res2 = ary2.sort(function(a,b){
    return a-b;
    })
    var res3 = ary3.sort(function(a,b){
    return b-a;
    })
    // The total formal parameters a and b of the parameter function of sort are the two items of the adjacent comparison when the array is sorted.
    console.log(res); // [1, 12, 24, 5, 56, 7, 87, 9, 92]
    console.log(res2); // [1,5,7,9,12,24,56,87,92]
    console.log(res3); // [92,87,56,24,12,9,7,5,1]
    // When no parameters are passed, those exceeding 10 can only be sorted according to the first rank.
    // When passing parameters, return a-b; // ascending order, return b-a; // descending order.
    

check array

  • includes
    Function: Check if an array contains an item
    Parameter: specific item
    Return value: boolean
    Whether to change the original array: no change

    [1,2,3].includes(2);
    true
    [1,2,3].includes(100);
    false
    
  • indexOf/lastlndexOf
    Not compatible with ie6-ie8:;
    Function: Get the index of the first/last occurrence of an item in the array (it can also be used to include an item)
    Parameters: n: the item to be detected m: if it is indexof, it is to search from the index m. If it is lastIndexOf, it is to stop the retrieval from index m
    Return value: -1 or specific index value
    Whether to change the original array: no change

    var ary = [1,2,3,4,5]
    var res = ary.indexOf(3);
    console.log(ary); // [1,2,3,4,5]
    console.log(res); //2
    var ary = ['a','b','c','d','c'];
    var res = ary.indexOf('c',3);
    console.log(res) //4
    
    var ary = ['a','b','c','d','c'];
    var res = ary.lastIndexOf('c',3);
    var res2 = ary.lastIndexOf('c',1);
    console.log(res); //2
    console.log(res2); //-1
    

iterate over the array

  • forEach
    Action: Iterate over each item in the array
    Parameters: function
    Return value: undefined
    Whether to change the original array: no change

    var ary = ['a','b','c']
    var res = ary.forEach(function(item,index,ary){
    console.log(item,index,ary);
    // a 0 ["a", "b", "c"]
    // b 1 ["a", "b", "c"]
    // c 2 ["a", "b", "c"]
    return item;
    })
    console.log(res) //undefined
    
  • map
    Role: map an array into a new array
    Parameters: function
    Return value: the new array after mapping
    Whether to change the original array: no change

    var ary = ['a','b','c']
    var res = ary.map(function(item,index,ary){
    return item+1;
    })
    console.log(res) // ['a1','b1','c1']
    
  • filter
    Function: Check whether all elements of the array meet the specified conditions
    Parameters: function ary.filter(function(item){})
    Return value: an array of matching elements
    Whether to change the original array: no change

    var ary = [1,2,3,4,5,6]
    var res = ary.filter(function(item){
    return item<3;
    })
    console.log(res) // [1,2]
    
  • some
    Function: Check whether the elements in the array meet the specified conditions
    Parameters: function ary.some(function(item,index,ary){})
    item: each item index: index ary: current array
    Return value: boolean
    Whether to change the original array: no change

    var ary = [1,2,3,4,5,6]
    var res = ary.some(function(item){
    return item<3;
    })
    console.log(res) // ture
    // 1 If one element satisfies the condition, the expression returns true , and the remaining elements will not be checked.
    // 2 Returns false if there are no elements that satisfy the condition.
    
  • every
    Function: Check whether all elements of the array meet the specified conditions
    Parameters: function ary.every(function(item){})
    Return value: boolean
    Whether to change the original array: no change

    var ary = [1,2,3,4,5,6]
    var res = ary.every(function(item){
    return item<3;
    })
    var res2 = ary.every(function(item){
    return item<7;
    })
    console.log(res) //false
    console.log(res2) // ture
    // 1 If an element in the array is detected that is not satisfied, the entire expression returns false , and the remaining elements are not checked.
    // 2 Returns true if all elements satisfy the condition.
    
    • reduce() and reduceRight()
      Both of these methods implement iterating over all the items of the array and then constructing a final return value. The reduce() method starts from the first item of the array and traverses to the end one by one. And reduceRight() starts from the last item of the array and traverses forward to the first item.
      Both methods take two parameters: a function to call on each item and (optionally) an initial value to use as the basis for the merge.
      The functions passed to reduce() and reduceRight() take 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function is automatically passed to the next item as the first argument. The first iteration happens on the second item of the array, so the first argument is the first item of the array and the second argument is the second item of the array.
      The following code uses reduce() to sum the array, and the array is initially added with an initial value of 10.
    var values = [1,2,3,4,5];
    var sum = values.reduceRight(function(prev, cur, index, array){
    return prev + cur;
    },10);
    console.log(sum); //25
    

application

deduplication

  • double loop + splice
    Idea: double-layer loop, outer loop elements, compare values ​​during inner loop. If the value is the same, delete the value.
function unique(arr) {
    for(var i=0;i<arr.length;i++) {
        for(var j=i+1;j<arr.length;j++) {
            if(arr[i] == arr[j]) {
                arr.splice(j,1);
                j--;
            }
        }
    }
    return arr;
}
  • indexOf + single loop
    Idea: Use indexOf to create a new empty result array, for loop the original array, determine whether the result array has the current element, if there is the same value, skip it, if not, push into the array.
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
}
  • sort + single loop
    Idea: Use the sort() sorting method, and then traverse and compare adjacent elements according to the sorted results.
function unique(arr) {
    if(!Array.isArray(arr)) {
        console.log('type eror')
        return;
    }
    arr.sort()
    var array = [arr[0]]
    for(var i=1;i<arr.length;i++) {
        if(arr[i] !== arr[i-1]) {
            array.push(arr[i])
        }
    }
    return array;
}
  • Using object properties cannot be the same
function unique(arr) {
    if(!Array.isArray(arr)) {
        console.log('type eror')
        return;
    }
    var array = []
    var obj = {}
    for(var i=0;i<arr.length;i++) {
        if(!obj[arr[i]]) {
            array.push(arr[i])
            obj[arr[i]] = 1
        } else {
            obj[arr[i]]++
        }
    }
    return array;
}
  • use includes
function unique(arr) {
  return arr.filter((item, index, arr) => {
    return arr.indexOf(item,0) === index; // The current element, the first index in the original array === the current index value, otherwise returns the current element.
  })
}
  • use recursion
function unique(arr) {
  var array = arr;
  var len = arr.length;
  array.sort((a, b) => {
    return a-b;
  })
  function loop(index) {
    if(index >=1) {
      if(array[index] === array[index -1]) {
        array.splice(index, 1)
      }
      loop(index-1)
    }
  }
  loop(len-1)
  return array;
}
  • Utilize the Map data structure
function arrayNonRepeatfy(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 there is this key value
          map.set(arr[i], true); 
        } else { 
          map.set(arr[i], false);   // If there is no such key value
          array.push(arr[i]);
        }
      }   
    return array ;
}
  • Use ES6 Set to deduplicate
function unique(arr) {
  return Array.from(new Set(arr))
}
var arr = ['a','d','d','d','a',1,2,3,3,4,true,true]
console.log(unique(arr)) // ["a", "d", 1, 2, 3, 4, true]

ES6 adds array methods

1. Array.from()

This method is used to convert two types of objects (array-like objects and traversable objects (including Set/Map data structures)) into real arrays. The essential characteristic of array-like objects is that they must have a length property.
Common array-like objects:

  • NodeList collection returned by DOM manipulation
  • The arguments object inside the function
let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3 // must be specified
}

// ES5 writing
var arr1 = [].slice.call(arrayLike); // ['a','b','c']

[].concat.apply([], arguments)
Array.prototype.slice.call(arguments) // apply can also

// ES6
var arr2 = Array.from(arrayLike)

Note: [].slice.call() Related concepts.

Array.from() can also receive a second parameter to implement a map-like function.

Array.from([1,2,3], (x) => x*x) // [1,4,9]

Array.from({length: 2}, () => 'jack') // ['jack','jack']

// The first parameter specifies the number of times the second parameter runs, which can be more flexible.

2. Array.of()

Make up for the deficiencies of the constructor Array(), because the behavior difference caused by the different number of parameters can basically be used to replace new Array()/Array()

Array.of(3) // [3]
Array(3) // [, , ,]

3. copyWithin()

Will copy the member at the specified position to another position within the current array, and modify the original array.
Receive parameters: all are numeric values, otherwise they will be automatically converted to numeric values. Negative values ​​are subtracted from the array length.
target: required, replace data from this position
start: optional, start reading data from this position, the default is 0. Negative value means reciprocal.
end: optional. Stop reading data at this position, which is equal to the length of the array by default. If negative, it means reciprocal.

[1,2,3,4,5].copyWithin(0,3) // [4,5,3,4,5]

// Platforms that do not deploy TypedArrayd's copyWithin method
[].copyWithin.call(new Init32Array([1,2,3,4,5]),0,3,4) // Init32Array [4,2,3,4,5]

4. find() and findIndex()

The find() method of an array instance finds the first matching array member. The first parameter is the callback function, and the second is the this object used to bind the callback function. The callback function until a member that returns true is found and returns that member, otherwise it returns undefined. The parameters of the callback function: the current value, the current position and the original array. The findIndex() method is similar, except that it returns the current position, and returns -1 if it does not match.

[1,4,-5,10].find((n) => n<0) // -5

The difference between the find() method and the indexOf() method is that the former can find NaN, while the latter cannot

[NaN].indexOf(NaN) // -1

Tags: Javascript array

Posted by jonah on Sun, 01 May 2022 23:09:19 +0300