Recently, in reviewing the knowledge points of javascript, I spent a few days of spare time to re-learn Array objects in MDN, and gained a new understanding and understanding of Array objects. Therefore, I decided to sort out these new contents and record them in order to motivate myself to continue learning.

First of all, we know that Array is a reference data type, which is essentially an object stored in heap memory, and the stack memory holds the reference address of the object in heap memory. An array in MDN is described as follows: An array is a list object of sorts. An array object has three properties: Length, constructor, and protoType.

  • length: Indicates the length of the array, that is, the number of elements in the array
  • constructor: represents the constructor that creates array objects, for all array instancesconstructorAre allArray
  • protoType: represents the prototype object of an array instance

There are many methods of array object, here the author summarizes nine categories according to his own understanding, one by one for the syntax and use of each method made a brief introduction.

1. Array creation

In ES6, we have two new Array creation methods: array. of and array. from.

  • Array created in direct quantity form

    const arr = []; / / an empty array
    const arr1 = [1.2.3.4.5];
    Copy the code
  • Constructor Array instantiation

    // 1. Direct instantiation
    const arr = new Array(1.2.3.4.5);
    console.log(arr); / / [1, 2, 3, 4, 5]
    
    // 2. Assign after instantiation
    const arr1 = new Array(a); arr1[0] = 1;
    arr1[1] = 2;
    arr1[2] = 3;
    arr1[3] = 4;
    arr1[4] = 5;
    console.log(arr1); / / [1, 2, 3, 4, 5]
    Copy the code

When we use the Array constructor to create an Array, we create an Array that is empty and has the length of that integer. When we pass in a string, we create an Array that has the length of that parameter.

When the Array constructor is passed a single integer 5, the Array created is [] and length is 5
const arr = new Array(5);
console.log(arr)    // [,,,,,] is an empty array with 5 Spaces
console.log(arr[0]) // undefined

// The Array constructor takes a single argument of '5' and creates an Array of ['5'];
const arr1 = new Array('5');
console.log(arr1) / / / '5'
Copy the code

To avoid ambiguity when Array constructors create arrays, ES6 adds array.of () methods to create arrays

  • Array.of() method

    Grammar: Array of (… Args), any of the parameters become the elements of the array in order

    The array.of () method creates an Array instance of mutable arguments, regardless of the number or type of arguments. The Array elements created are the arguments passed in.

    const arr = Array.of(5);
    console.log(arr)  / / [5]
    const arr1 = Array.of(1.2.3.4.5);
    console.log(arr1) / / [1, 2, 3, 4, 5]
    const arr2 = Array.of(undefined);
    console.log(arr2) // [undefined]
    Copy the code

ES6 also added the array.from () method, which creates a new, shallow-copy instance of an Array from a class Array or iterable.

  • Array.from() method

    Syntax: array. from(arrayLike, mapFn, thisArg)

    ArrayLike is an array-like object (an object with a length attribute and several index attributes) or iterable object (Set, Map, arguments, etc.), mapFn is an optional argument, each element of the new array will execute this callback function, thisArg is optional, Specifies this object when mapFn is executed.

    // 1.String generates an array
    const str = 'string';
    const arr = Array.from(str);
    console.log(arr); // ['s','t','r','i','n','g']
    
    // 2.Set generates an array
    const set = new Set(['s'.'e'.'t']);
    const arr1 = Array.from(set);
    console.log(arr1); // ['s','e','t']
    
    // 3.Map generates an array
    const map = new Map([[1.'m'], [2.'a'], [3.'p']]);
    const arr2 = Array.from(map);
    const arr3 = Array.from(map.values());
    const arr4 = Array.from(map.keys());
    console.log(arr2); // [[1,'m'],[2,'a'],[3,'p']]
    console.log(arr3); // ['m','a','p']
    console.log(arr4); / / [1, 2, 3];
    
    // 4. Arguments generate an array
    function f() {
      return Array.from(arguments);
    }
    console.log(f(1.2.3.4.5)); / / [1, 2, 3, 4, 5]
    
    // 5. Iterables generate arrays
    const numbers = {
      *[Symbol.iterator](){
        yield 1;
        yield 2;
        yield 3; }}const arr5 = Array.from(numbers,value= > value +1);
    console.log(arr5); / / / 2 and 4
    
    // specify the callback function
    const arr6 = Array.from([1.2.3.4.5].item= > item * 2);
    console.log(arr6); / /,4,6,8,10 [2]
    
    // 7. Specify the callback function and the this object that executes the callback
    const helper = {
      diff:1.add(value) {
        return value + this.diff; }}const arr7 = Array.from([1.2.3.4.5],helper.add,helper); 
    console.log(arr7); / /,3,4,5,6 [2]
    
    // 8. Application: Use array. from and Set to implement Array de-duplication
    function unique(arr) {
      return Array.from(new Set(arr));
    }
    console.log(unique([1.1.2.2.3.3.4.4.5.5])); / / [1, 2, 3, 4, 5]
    Copy the code
2. Built-in iterators

There are three types of collection objects in ES6: Array, Map, and Set. These three types of collection objects, including other iterables, have three built-in iterators:

  1. entries(): returns an iterator with multiple key-value pairs
  2. keys(): returns an iterator with the values of all the key names of the collection
  3. values(): returns an iterator with the value of the collection

If you understand the concept of iterators, you know that each iterator object has a next() method that returns a result object each time it is called. The result object has two attributes: value, which represents the next value to be returned; The other is done, a Boolean that returns true if there is no data to return.

  • Entries () an iterator

    Calling iterators returned by Entries () Each time the next() method is called, it returns a result object whose value is an array containing the keys and values of each element in the collection. If the object being traversed is an array, the first element is a numeric index. In the case of a Set, the first element and the second element are values. In the case of a Map collection, the first element is the key name. Here is an example of an array.

    const colors = ['red'.'yellow'.'blue'];
    const iter = colors.entries();
    console.log(iter.next()); // { value: [0,'red'], done: false}
    console.log(iter.next()); // { value: [1,'yellow'], done: false}
    console.log(iter.next()); // { value: [2,'blue'], done: false}
    console.log(iter.next()); // { value: undefined, done: true}
    Copy the code
  • The keys () an iterator

    Each time the next() method is called, the iterator returned by keys() returns a value that is the key name of the element that exists in the collection.

    const colors = ['red'.'yellow'.'blue'];
    const iter1 = colors.keys();
    console.log(iter1.next()); // { value: 0, done: false}
    console.log(iter1.next()); // { value: 1, done: false}
    console.log(iter1.next()); // { value: 2, done: false}
    console.log(iter1.next()); // { value: undefined, done: true}
    Copy the code
  • Values () iterators

    Each time the next() method is called, the value returned in the result object is the value of the element in the collection.

    const colors = ['red'.'yellow'.'blue'];
    const iter2 = colors.values();
    console.log(iter2.next()); // { value: 0, done: false}
    console.log(iter2.next()); // { value: 1, done: false}
    console.log(iter2.next()); // { value: 2, done: false}
    console.log(iter2.next()); // { value: undefined, done: true}
    Copy the code

In addition, the default iterator for Array and Set is VALUES (), the default iterator for Map is entries(), and the default iterator for for… In the of loop, the default iterator is used if it is not explicitly specified.

3. Array detection and array element detection

Array.isarray; every(), some();

  • Array.isarray () : Checks whether an object is an Array object

    Grammar: Array. IsArray (obj)

    Returns true if the object passed is Array, false otherwise.

    console.log(Array.isArray([])); // true
    console.log(Array.isArray([1])); // true
    console.log(Array.isArray(new Array())); // true
    console.log(Array.isArray({})); // false
    console.log(Array.isArray(null)); // false
    console.log(Array.isArray(undefined)); // false
    Copy the code
  • Every () : checks whether all elements of an array pass the test of the specified function, returning a Boolean value

    Arr. Every (callback(element, index, array), thisArg)

    The element parameter is the current value for detection. Index Indicates the index of the current value. Array (optional) is the current array that calls every. ThisArg is the this object used when executing callback

    [18.32.4.120.60].every(x= > x > 10); // false
    [18.32.14.120.60].every(x= > x > 10); // true
    Copy the code
  • Some () : Checks whether an element in the array passes the test of the specified function, and returns a Boolean

    Syntax: arr.some(callback(element, index, array), thisArg)

    [2.1.4.8.7].some(x= > x > 10); // false
    [2.1.14.8.7].some(x= > x > 10); // true
    Copy the code
4. Array reorder

There are two methods for reordering arrays: sort() and reverse()

  • Sort () : Sorts the elements of an array using an in-place algorithm and returns the array. The default sort order is to convert elements to strings and then sort them according to a character-by-character Unicode point, which alters the array.

    Syntax: arr.sort(compareFn(firstEl, secondEl))

    Where, compareFn is optional and is used to specify functions in a certain order. If a and B are the two elements to be compared

    • If ‘compareFn(a, b) < 0, then A will be ranked before B
    • If compareFn(a, b) = 0, then the relative positions of a and B remain the same
    • If compareFn(a, b) > 0, then b will be ranked before A
    // Sort the array in ascending or descending order
    const arr = [1.3.2.5.4];
    console.log(arr.sort((a, b) = > a - b)); / / [1, 2, 3, 4, 5]
    console.log(arr.sort((a, b) = > b - a)); / /,4,3,2,1 [5]
    Copy the code

As we know, there are eight common sorting algorithms:

Stable: bubble sort O(n2), insertion sort O(n2), radix sort O(logRB), merge sort O(nlogn)

Unstable: Select sort O(n2), Hill sort O(nlogn), quick sort O(nlogn), heap sort O(nlogn)

What does sort() do at the bottom and what is the time complexity of its algorithm?

The implementation of sort() is different in different browsers. Here we mainly study the source code of sort() under V8 engine. We find that the insertion sort is used for arrays with length <=10, and the insertion sort + quicksort is used for arrays with length >10. Here’s a snippet of the source code:

// Insertion sort is faster for short arrays.
if (to - from< =10) {
  InsertionSort(a, from, to);
  return;
}
if (to - from > 1000) {
  third_index = GetThirdIndex(a, from, to);
} else {
  third_index = from + ((to - from) > >1);
}
Copy the code

Of course, this is a pre-chrome 70 implementation of sort(). Since Chrome 70, the V8 team has updated the sort() method to use the Timesort algorithm, which I didn’t delve into here.

  • Reverse () : Reverses the elements in an array and returns the array. This method changes the original array

    Grammar: arr. Reverse ()

    const arr = [1.2.3.4.5];
    console.log(arr.reverse()); / / [1, 2, 3, 4, 5]
    Copy the code
5. Operations on array elements

For the elements of the array, there are mainly operations such as adding, deleting and modifying array elements, including:

Add: push(), unshift()

Delete: pop(), shift()

Modify: fill(), copyWithin()

  • Push () : Adds one or more elements to the end of an array and returns the array’s new length.

    Grammar: arr. Push (element1,… ,elementN)

    The push method is generic and can be used with call() or apply() on array-like objects.

    // Add elements to the array
    const arr = [1.2.3.4.5];
    const total = arr.push(6.7.8.9.10);
    console.log(arr); / /,2,3,4,5,6,7,8,9,10 [1]
    console.log(total); // 10 total is the new length value of the array
    
    // Merge two arrays with apply()
    const arr1 = [1.2.3.4.5];
    const arr2 = [6.7.8.9.10];
    Array.prototype.push.apply(arr1,arr2);
    console.log(arr1); / /,2,3,4,5,6,7,8,9,10 [1]
    
    // Class array object application
    const obj = {
      length: 0.addElem: function(elem){ [].push.call(this, elem) } 
    };
    obj.addElem({});
    obj.addElem({});
    console.log(obj); // {0: {}, 1: {}, length: 2, addElem: ƒ}
    Copy the code
  • Pop () : Removes the last element in the array and returns it. Returns undefined when the array is empty.

    Grammar: arr. Pop ()

    The POP method is also generic and can be used with call() or apply() on array-like objects.

    // Remove the last element of the array
    const arr = [1.2.3.4.5];
    const elem = arr.pop();
    console.log(arr); / / [1, 2, 3, 4]
    console.log(elem); / / 5
    Copy the code
  • Unshift () : Adds one or more elements to the beginning of an array and returns the new length of the array.

    Grammar: arr. Unshift (element1,… ,elementN)

    Unshift can also be applied to array-like objects using call() or apply() methods.

    // Add elements to the array
    const arr = [1.2.3.4.5];
    const total = arr.unshift(6.7.8.9.10);
    console.log(arr); / /,7,8,9,10,1,2,3,4,5 [6]
    console.log(total); / / 10
    
    // Merge arrays
    const arr1 = [1.2.3.4.5];
    const arr2 = [6.7.8.9.10];
    Array.prototype.unshift.apply(arr1,arr2);
    console.log(arr1); / /,7,8,9,10,1,2,3,4,5 [6];
    Copy the code
  • Shift () : Removes the first element in the array and returns that element. Returns undefined when the array is empty

    Grammar: arr. The shift ()

    Shift can also be applied to array-like objects using call() or apply() methods.

    const arr = [1.2.3.4.5];
    const elem = arr.shift();
    console.log(arr); / / 5-tetrafluorobenzoic [2]
    console.log(elem); / / 1
    Copy the code

We know that stacks are last-in, first-out, and queues are last-in, last-out. Therefore, we can use the array push() and pop() to implement the stack structure, and push() and shift() to implement the queue structure.

// Stack structure last in first out
const Stack = function() {
    this.data = [];
    this.insert = push;
    this.delete = pop;
    this.clear = clear;
    this.length = length;
}
const push = function(element) {
    this.data.push(element);
    return this.data.length;
}
const pop = function() {
    return this.data.pop();
}
const clear = function() {
    this.data.length = 0;
}
const length = function() {
    return this.data.length;
}

const s = new Stack();
s.insert('first');
s.insert('second');
console.log(s.data); // ['first','second']
s.delete();
console.log(s.data); // ['first']
s.clear();
console.log(s.data); / / []
Copy the code
// Queue structure back in back out
const Queue = function() {
    this.data = [];
    this.insert = push;
    this.delete = shift;
    this.clear = clear;
    this.length = length;
}
const push = function(element) {
    return this.data.push(element);
}
const shift = function() {
    return this.data.shift();
}
const clear = function() {
    this.data.length = 0;
}
const length = function() {
    return this.data.length;
}

const q = new Queue();
q.insert('first');
q.insert('second');
console.log(q.data); // ['first','second']
q.delete();
console.log(q.data); // ['second']
q.clear();
console.log(q.data); / / []
Copy the code

Further thinking, we can realize DFS through the stack: first, the root node is pushed onto the stack, and then check whether the node has child nodes after it is removed from the stack. If there are child nodes, the node is pushed into the stack in reverse order, and then removed from the stack, and the child nodes are pushed into the stack in reverse order. BFS is implemented through queues: first, the root node is enqueued, and then the node is dequeued to check whether it has child nodes. If there are child nodes, the node is enqueued in sequence, and then the node is dequeued in sequence

// the stack implements DFS
function deepTraversal(node) {
    const nodelist = [];
    if(node) {
        const stack = [];
        stack.push(node); // The root node is pushed
        while(stack.length ! = =0) {
            const childItem = stack.pop(); // unstack (last element of array)
            nodelist.push(childItem); 
            const childrenList = childItem.children;// Get the children of the node that is off the stack, ensuring that the children are off the stack first
            for(let i = childrenList.length-1; i >=0; i--) { stack.push(childrenList[i]);// The child node is pushed in reverse order}}returnnodelist; }}Copy the code
// The queue implements BFS
function wideTraversal(node) {
    const nodelist = [];
    if(node) {
        const queue = [];
        queue.push(node); // The root node is queued
        while(queue.length ! = =0) {
            const childItem = queue.shift(); // Queue out (first element of array)
            nodelist.push(childItem);
            const childrenList = childItem.children; // Get the children of the queue node
            for(let i = 0; i <= childrenList.length -1; i++) { queue.push(childrenList[i]);// The child nodes are queued in sequence to ensure that the parent node exits the queue first}}returnnodelist; }}Copy the code
  • Fill () : Fills an array with a fixed value from the start index to the end index (that is, the element that replaces the specified position in the array), excluding the end index. Returns the modified array.

    Syntax: arr.fill(value, start, end)

    Value is the value used to populate the array elements. The default value is 0. If start is negative, the start index is length+start. This parameter is optional. The default value is length. When end is negative, the end index is length+end. This parameter is optional.

    Fill is a generic method, and an array-like object can call fill either through call() or apply().

    const arr1 = [1.2.3.4.5].fill(4);
    const arr2 = [1.2.3.4.5].fill(4.1.2);
    const arr3 = [1.2.3.4.5].fill(4.4.4);
    const arr4 = [1.2.3.4.5].fill(4, -2);
    const arr5 = [1.2.3.4.5].fill(4, -4, -1);
    const arr6 = Array(5).fill(4);
    const arr7 = [].fill.call({length: 5},4);
    console.log(arr1);   / /,4,4,4,4 [4]
    console.log(arr2);   / /,4,3,4,5 [1]
    console.log(arr3);   / / [1, 2, 3, 4, 5]
    console.log(arr4);   / /,2,3,4,4 [1]
    console.log(arr5);   / /,4,4,4,5 [1]
    console.log(arr6);   / /,4,4,4,4 [4]
    console.log(arr7);   // {0: 4, 1: 4, 2: 4, 3: 4, 4: 4, length: 5}
    Copy the code
  • CopyWithin () : shallowly copies part of an array to another location in the same array and returns it without changing the length of the original array. Returns the changed array.

    Syntax: arr. CopyWithin (target, start, end)

    Target is the location where the sequence is copied to the index. When target is negative, the copied position index is length+target. When target is greater than length, no copying occurs. When target is after start, the copied sequence is modified to match arr.length.

    Start is the initial index to start copying elements. The default value is 0. When start is negative, the start index is length+start.

    End is the terminating index of the element that starts copying, excluding elements at that position. The default value is arr.length, and when end is negative, the terminating index is length+end.

    const arr1 = [1.2.3.4.5].copyWithin(-2);
    const arr2 = [1.2.3.4.5].copyWithin(0.3);
    const arr3 = [1.2.3.4.5].copyWithin(0.3.4);
    const arr4 = [1.2.3.4.5].copyWithin(3.1.4);
    const arr5 = [1.2.3.4.5].copyWithin(1, -3, -1);
    const arr6 = [1.2.3.4.5].copyWithin(1, -3, -4);
    const arr7 = [].copyWithin.call({length: 5.3: 1},0.3);
    console.log(arr1);   / /,2,3,1,2 [1]
    console.log(arr2);   / /,5,3,4,5 [4]
    console.log(arr3);   / / (4, 2, 3, 4, 5)
    console.log(arr4);   / /,2,3,2,3 [1]
    console.log(arr5);   / /,3,4,4,5 [1]
    console.log(arr6);   / / [1, 2, 3, 4, 5]
    console.log(arr7);   // {0: 1, 3: 1, length: 5}
    Copy the code
6. Search and filter array elements

Js array search for an element, including (), lastIndexOf() and ES6 includes(), find(), findIndex(). Filter () finds all elements that match a condition against an array.

  • IndexOf () : returns the indexOf the first element in the array, or -1 if none exists. Look backwards from the front of the array

    Syntax: arr.indexof (searchElment, fromIndex:option)

    SearchElement to find elements, fromIndex optional, to begin to find the location of fromIndex is negative, say from the bottom first | fromIndex | element began to find (can also be ShunShu fromIndex + arr. Length), The search order is still front to back.

    // Find the position of the element in the array
    const arr = [1.2.3.4.5];
    console.log(arr.indexOf(2));     //  1
    console.log(arr.indexOf(6));     // -1
    console.log(arr.indexOf(3.3));   // -1
    console.log(arr.indexOf(2, -1));  // -1
    console.log(arr.indexOf(4, -3));  / / 3
    Copy the code
  • LastIndexOf () : Returns the index of the last element in the array, or -1 if none exists. Look forward from the back of the array.

    Syntax: arr. LastIndexOf (searchElement, fromIndex)

    SearchElement to find elements, fromIndex optional, for from now on location to begin the reverse lookup, when fromIndex negative, said from the array from the first | fromIndex | element began to find (can also be ShunShu fromIndex + arr. Length), The search sequence is still from back to front.

    const arr = [1.2.3.4.5.3.1];
    console.log(arr.lastIndexOf(3));     //  5
    console.log(arr.lastIndexOf(6));     // -1
    console.log(arr.lastIndexOf(3.3));   / / 2
    console.log(arr.lastIndexOf(3, -3));  / / 2
    console.log(arr.lastIndexOf(3, -1));  / / 5
    Copy the code
  • Includes () : Finds if an array contains the specified element, returning true if it does, false otherwise.

    Syntax: Arr. incluedes(searchElement, fromIndex)

    SearchElment to find elements, fromIndex optional, start from fromIndex index search, when the negative fromIndex from arr. Length + fromIndex index began to find (or reciprocal | fromIndex | element), If the calculated index is still less than 0, the entire array is searched, in the same order as before.

    arr = [1.2.3.4.5];
    console.log(arr.includes(1));      // true
    console.log(arr.includes(3.2));    // true
    console.log(arr.includes(3, -2));   // false
    console.log(arr.includes(5, -10));  // true
    Copy the code
  • Find () : Returns the value of the first element in the array that satisfies the test function providing the test, or undefined if it does not.

    Arr. Find (callback(Element, index, array),thisArg)

    Callback is a function executed on each item of the array, with three arguments: Element is the current iterated element; Index (Optional) Indicates the current traversal index. Array is also optional, for an array that calls findIndex. ThisArg optional, this object when the callback is executed.

    // Find an object in the array with its properties
    const inventory = [
      {name: 'apples'.quantity: 2},
      {name: 'bananas'.quantity: 0},
      {name: 'cherries'.quantity: 5}]console.log(inventory.find(fruit= > fruit.name === 'cherries')); 
    // {name: 'cherres', quantity: 5}
    
    // Find the first prime number in the array
    function isPrime(element) {
      let start = 2;
      while(start <= Math.sqrt(element)) {
        if(element % start++ < 1) {
          return false; }}return element > 1;
    }
    console.log([4.6.8.12].find(isPrime));      // undefined
    console.log([4.5.8.12].find(isPrime));      / / 5
    console.log([3.4.5.7.8.12].find(isPrime));  / / 3
    Copy the code
  • FindIndex () : Returns the index of the first element in the array that satisfies the provided test function. If not, -1 is returned.

    Syntax: arr. FindIndex (callback(Element, index,array),thisArg)

    Callback is a function executed on each item of the array, taking three arguments: Element is the element currently iterated over; Index (Optional) Indicates the current traversal index. Array (optional) Is the array to which findIndex is called. ThisArg optional, this object when callback is executed.

    // Find the index of the first prime element in the array
    function isPrime(element) {
      let start = 2;
      while(start <= Math.sqrt(element)) {
        if(element % start++ < 1) {
          return false; }}return element > 1;
    }
    console.log([4.6.8.12].findIndex(isPrime));    // -1
    console.log([4.6.7.12].findIndex(isPrime));    / / 2
    console.log([4.5.6.7.12].findIndex(isPrime));  / / 1
    Copy the code
  • Filter () : Creates a new array containing all elements that pass the tests of the provided function.

    Const newArray = arr. Filter (callback(Element,index,array),thisArg)

    Where callback is a function that tests each element of the array. Returning true indicates that the element passed the test and is retained, false does not. There are three arguments: element is the current element; Index indicates the current index. Array is the array for calling filter. ThisArg is the this object when callback is executed.

    // Filter the elements that meet the criteria
    const arr = [12.5.10.24.48];
    const arr1 = arr.filter(element= > element > 10);
    const arr2 = arr.filter(element= > element <= 10);
    console.log(arr1); / /,24,48 [12]
    console.log(arr2); / / (5, 10]
    
    // Filter invalid entries in JSON
    const arr = [
      { id: 15 },
      { id: -1 },
      { id: 0 },
      { id: 3 },
      { id: 12.2}, {}, {id: null},
      { id: NaN },
      { id: 'undefiend'}];let invalidEntries = 0;
    function filterByID(item) {
      if(item.id ! = =undefined 
         && typeof(item.id) === 'number'&&!isNaN(item.id) && item.id ! = =0) {
        return true;
      }
      invalidEntries++;
      return false;
    }
    const newArr = arr.filter(filterByID);
    console.log(newArr);          // [{id: 15},{id: -1},{id: 3},{id: 12.2}]
    console.log(invalidEntries);  / / 5
    Copy the code
7. Array merge and cut

Js provides array merge and split methods, you can operate on one or more arrays.

Methods for merging are: concat(), join()

Methods of cutting are: slice(), splice()

  • Concat () : Merges two or more arrays. This method returns a new array without changing the original array.

    Const newArray = oldarray.concat (Array1,… ,ArrayN)

    If concat’s argument is empty, a shallow copy of the existing array that called the method is returned (that is, a shallow copy of oldArray).

    // Merge multiple arrays
    const arr1 = [1.2.3];
    const arr2 = [4.5.6];
    const arr3 = ['a'.'b'.'c'];
    const arr = arr1.concat(arr2,arr3);
    console.log(arr); / / [6, 'a', 'b', 'c']
    
    // Returns a shallow copy of the original array
    const oldArray = [
      {
        person: {
        	name: 'zhang'.age: 28
      	},
        city: 'wuhan'
      },
      {
        person: {
          name: 'wang'.age: 29
        },
        city: 'shenzheng'}]const newArray = oldArray.concat();
    oldArray[0].person.age = 27;
    console.log(newArray); 
    / / [{person: {name: "zhang", the age: 27}, city: 'wuhan'}, {person: {name: "wang", the age: 29}, city: 'shenzhen'}]
    Copy the code
  • Join () : Delimits all elements of a specified array or array-like object into a string and returns it. If the array has only one item, it is returned without a delimiter.

    Grammar: arr. Join (separator)

    Separator Optional, specifies the separator for each element of the join array. If separator is an empty string (“), there are no characters between the array elements. If an element is undi25th or NULL, it is converted to an empty string.

    // Join the array
    const arr = ['Winter'.undefined.'Is'.null.'Comming'];
    const str = arr.join();
    const str1 = arr.join(', ');
    const str2 = arr.join('_');
    const str3 = arr.join(' ');
    console.log(str);    // Winter,,Is,,Comming
    console.log(str1);   // Winter,, Is,, Comming
    console.log(str2);   // Winter__Is__Comming
    console.log(str3);   // WinterIsComming
    
    // Connect class array objects
    function f(a,b,c) {
      const s = Array.prototype.join.call(arguments);
      console.log(s); 
    }
    f(1.'cold'.true); // 1,cold,true
    Copy the code
  • Slice () : Returns a new array object that is a shallow copy of the array determined by begin and end (including begin, but not end). The original array does not change.

    Syntax: arr.slice(begin, end)

    Begin (optional) Cuts elements from the index. If begin is omitted, slice begins at index 0, and if begin is negative, the slice begins at the last element (or the sequential index arr.length+begin).

    End (optional) ends the cutting of the original array elements at the index. If end is omitted, slice extracts to the end of the array. If end is negative, it ends at the penultimate element of the array (or the sequential index arr.length+end). If end is greater than the length of the array, slice extracts to the end of the array.

    // Returns part of an existing array
    const arr = ['Banana'.'Orange'.'Lemon'.'Apple'.'Mango'];
    const fruit = arr.slice();
    const fruit1 = arr.slice(1.3);
    const fruit2 = arr.slice(-1.3);
    const fruit3 = arr.slice(3, -1);
    const fruit4 = arr.slice(-1, -3);
    const fruit5 = arr.slice(-3, -1);
    console.log(fruit);    // ['Banana','Orange','Lemon','Apple','Mango']
    console.log(fruit1);   // ['Orange','Lemon']
    console.log(fruit2);   / / []
    console.log(fruit3);   // ['Apple']
    console.log(fruit4);   / / []
    console.log(fruit5);   // ['Lemon','Apple']
    
    // Class array object call
    function list() {
      return [].slice.call(arguments);
    }
    list(1.2.3.4.5);   / / [1, 2, 3, 4, 5]
    Copy the code
  • Splice () : Modifies an array by removing or replacing elements of an existing array or adding new elements in place, and returns the modified contents as an array. This method changes the original array. The return value is an array of deleted elements.

    Syntax: arr.splice(start, deleteCount, item1,item2,…)

    Where, start specifies the starting position of the modification (including the elements at that position). If the length of the array exceeds, the content is added from the end of the array. If it is negative, it indicates the element from the penultimate of the array. If the absolute value of a negative number is greater than the length of the array, it indicates the starting position is the 0th bit.

    DeleteCount Optional number of array elements to remove. If deleteCount is greater than or equal to length-start, all elements after start are deleted. If deleteCount is 0 or negative, no element after start is removed. At least one new element should be added in this case.

    item1,item2,… Represents the element to be added to the array, starting at the start position. If not specified, splice removes only the element.

    const arr1, arr2, arr3, arr4, arr5 = [1.2.3.4.5];
    
    console.log(arr1.splice(2));          / / / three, four, five
    console.log(arr1);                    / / [1, 2]
    
    console.log(arr2.splice(1.5));        / / 5-tetrafluorobenzoic [2]
    console.log(arr2);                    / / [1]
    
    console.log(arr3.splice(-1.3.4.5));   / / [5]
    console.log(arr3);                    / /,2,3,4,4,5 [1]
    
    console.log(arr4.splice(-1, -1.4.5));  / / []
    console.log(arr4);                    / /,2,3,4,5,4,5 [1]
    
    console.log(arr5.splice(6.2.4.5));    / / []
    console.log(arr5);                    / /,2,3,4,5,4,5 [1]
    Copy the code
8. Array traversal

The methods of traversing the number group in JS include forEach(), map(), reduce() and reduceRight().

  • ForEach () : Iterates through each element of the array, executing the given function once. ForEach cannot get out of the loop unless it throws an exception and does nothing to uninitialized values. The return value is undefined.

    Arr. ForEach (callback(currentValue, index, array), thisArg)

    Callback is a function that iterates through each element and takes three arguments:

    CurrentValue is the element currently traversed; Index (Optional) Indicates the current traversal index. Array This parameter is optional. Array is the array to execute forEach.

    ThisArg optional, this object when the callback function is executed.

    // Iterate over the sparse array
    const arrSparse = [1.3.7];
    let numCallbackRuns = 0;
    arrSparse.forEach(function(element) {
      console.log(element); numCallbackRuns++; });console.log('numCallbackRuns: ',numCallbackRuns);
    
    / / 1
    / / 3
    / / 7
    // numCallbackRuns: 3
    Copy the code
  • Map () : Creates a new array that iterates over each element of the array and returns the value after executing the specified function. It doesn’t change the original array.

    Const newArray = arr. Map (callback(currentValue, index, array),thisArg)

    Callback is a function that generates a new array element and takes three arguments:

    CurrentValue is the element currently traversed; Index (Optional) Indicates the current traversal index. Array (optional) Is the array to call map.

    ThisArg is the this object that executes the callback function.

    // Square each element in the array
    const arr = [1.2.3.4.5];
    const newArr = arr.map(item= > Math.pow(item,2));
    console.log(newArr);    / /,4,9,16,25 [1]
    
    // map formats the objects in the array
    const arr = [
      {key: 1.value: 10},
      {key: 2.value: 20},
      {key: 3.value: 30}];const newArr = arr.map(function(obj) {
      const rObj = {};
      rObj[obj.key] = obj.value;
      return rObj;
    })
    console.log(newArr); // [{1:10},{2:20},{3:30}]
    Copy the code
  • Reduce () : Executes a specified Reducer function (ascending) on each element in the array and summarizes its results into a single return value.

    Arr. Reduce (Callback (Accumulator, currentValue, Index, array), initialValue)

    Callback is a function that iterates through each element and has four arguments:

    Accumulator is the return value of the accumulator’s accumulated callback, that is, the accumulated value returned from the previous call.

    CurrentValue is the element currently traversed; Index (Optional) Indicates the current traversal index. Array This parameter is optional. It is the array that calls reduce().

    InitialValue The value of the first argument when the callback function is called for the first time. If not provided, the first element of the array will be used and the element will be skipped through. The return value is the result of the cumulative processing of the function.

    // Add all the values in the array
    const arr = [1.2.3.4.5];
    const total = arr.reduce((acc,cur) = > acc + cur, 0); 
    console.log(total);    / / 15
    
    // Convert a two-dimensional array to a one-dimensional array
    const arr1 = [[1.2], [3.4], [5.6]].const flattened = arr1.reduce((acc, cur) = > acc.concat(cur), []);
    console.log(flattened);    / / [6]
    
    // Count the number of occurrences of each element in the array
    const names = ['Alice'.'Bob'.'Tiff'.'Bruce'.'Alice'];
    const countNames = names.reduce(function(allNames, name){
      if(name in allNames){
        allNames[name]++;
      } else {
        allNames[name] = 1;
      }
    	return allNames
    },{});
    console.log(countNames);  // {'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1}
    
    // Array decrement
    const arr2 = [1.3.5.7.5.3.1];
    const newArr = arr2.reduce((acc, cur) = > {
      if(! acc.includes(cur)) { acc.push(cur) }returnacc; } []);console.log(newArr);    / /,3,5,6 [1]
    Copy the code
  • ReduceRight () : Accept a function as an accumulator to iterate over the elements of a group of numbers from right to left and summarize the results into a single value.

    Arr. ReduceRight (Callback (Accumulator, currentValue, Index, array), initialValue)

    Callback is a callback function that iterates through each element and takes four arguments:

    Accumulator is the return value of the callback accumulated by the accumulator, that is, the return value from the previous call to the callback function.

    CurrentValue is the element currently traversed; Index (Optional) Indicates the current traversal index. Array is the array to call callback.

    InitialValue Is the value of the accumulator when the callback function is called for the first time. This parameter is optional. If no initial value is provided, the last element of the array is used as the initial value and traversal skips that element. The return value is the return value of the cumulative execution.

    // Evaluates the sum of array elements
    const arr = [0.1.2.3.4];
    const sum = arr.reduceRight((acc, cur) = > acc + cur, 0);
    console.log(sum);    / / 10
    
    // Flatten a two-dimensional array
    const arr2 = [[0.1], [2.3], [4.5]].const flattened = arr2.reduceRight((acc, cur) = > acc.concat(cur));
    console.log(flattened);  / /,5,2,3,0,1 [4]
    
    // The difference between reduce and reduceRight
    const arr3 = ['1'.'2'.'3'.'4'.'5'];
    const arr4 = arr3.reduce((acc, cur) = > acc + cur);
    const arr5 = arr3.reduceRight((acc, cur) = > acc + cur);
    console.log(arr4);    / / '12345'
    console.log(arr5);    / / '54321'
    Copy the code
9. Array flattening

In js, there may be cases where arrays are nested (that is, the elements of the array are still arrays) and we want to expand all the elements to form a one-dimensional array, that is, the array flattening. The flat() or flatMap() method is used.

  • Flat () : Recursively traverses the array at a specified depth and merges all elements with elements in the traversed subarray into a new array.

    Syntax: const newArr = arr,flat(depth)

    Depth Optional. Specifies the nesting depth of the nested array to be extracted. The default value is 1. The return value is a flattened new array.

    // Flat the nested array
    const arr1 = [1.2[3.4]].const arr2 = arr1.flat();
    console.log(arr2);    / / [1, 2, 3, 4]
    
    const arr3 = [1.2[3.4[5.6]]];
    const arr4 = arr3.flat();
    const arr5 = arr3.flat(2);
    console.log(arr4);    / / [1, 2, 3, 4, 5, 6]]
    console.log(arr5);    / / [6]
    
    // Use Infinity to expand a nested array to any depth
    const arr6 = [1.2[3.4[5.6[7.8[9.10]]]]];
    const arr7 = arr6.flat(Infinity);
    console.log(arr7);    / /,2,3,4,5,6,7,8,9,10 [1]
    
    // Flattening removes an empty item from the array
    const arr8 = [1.2.4.5];
    const arr9 = arr8.flat();
    console.log(arr9);    / /,2,4,5 [1]
    Copy the code

    Of course, we can also flatten nested arrays by recursively + isArray:

    const arr = [1.2.3[1.2.3[1.2.3[1.2.3]]]];
    function flatten(arr) {
      return arr.reduce((acc, cur) = > acc.concat(Array.isArray(cur)? flatten(cur):cur),[]) }console.log(flatten(arr)); / /,2,3,1,2,3,1,2,3,1,2,3 [1]
    Copy the code
  • FlatMap () : First map each element using the mapping function, then compress the result into a new array. It is almost identical to a map connected to a flat with a depth value of 1, but more efficient.

    Syntax: const newArr = arr.flatMap(Callbakc (cuttrentValue, index, array),thisArg)

    Callback is a mapping function that maps each element and has three parameters:

    CurrentValue is the element currently being processed; Index (optional) Indicates the index of the current element. Array Is an optional array to call the flatMap.

    ThisArg optional, this object when callback is executed.

    // The difference between map() and flatMap(
    const arr = [1.2.3.4.5];
    const arr1 = arr.map(x= > [x * 2]);
    const arr2 = arr.flatMap(x= > [x * 2]);
    const arr3 = arr.flatMap(x= > [[x * 2]]);
    
    console.log(arr1);  / / [[2], [4], [6], [8], [10]]
    console.log(arr2);  / /,4,6,8,10 [2]
    console.log(arr3);  / / [[2], [4], [6], [8], [10]]
    Copy the code
【 References 】:

Developer.mozilla.org/zh-CN/docs/…