Create an array

We can run into some really weird problems when we create arrays. Such as:

Use the Array() constructor

Array(a)/ / []
Array(3) / / /,,,
Array(1.2.3) / / [1, 2, 3]
Copy the code

In the code above, the Array() method returns different results with no arguments, one argument, or three arguments. This is because when an Array is created using the Array() constructor, the Array constructor creates a JavaScript Array based on the given element, except when there is only one argument and it is a number

Let’s look at array.of ()

Array.of(1.2.3) / / [1, 2, 3]
Array.of(1) / / [1]
Array.of(1).length / / 1
Copy the code

The array.of () method converts a set of values to an Array. This method compensates for the Array constructor Array(). Array() behaves differently because of the number of arguments.

A static method of an array

  • Array.from() creates a new Array instance from an array-like object or iterable
Array.from('foo');
// [ "f", "o", "o" ]
Copy the code
  • Array.isarray () is used to determine whether a variable is an Array object
Array.isArray([1.2.3]);
// true
Array.isArray({foo: 123});
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false

Copy the code
  • Array.of() creates a new Array instance based on a set of parameters, supporting any number and type of parameters
Array.of(7);       / / [7]
Array.of(1.2.3); / / [1, 2, 3]

Array(7);          // [,,,,,,]
Array(1.2.3);    / / [1, 2, 3]

Copy the code

Array loop execution efficiency

Js common several loop execution efficiency, due to some deviation in the actual test, SO I take the average of 10 test results to see the efficiency comparison of various loops (Chrome 81 is used in the test environment). Test result comparison: for > forEach > while > map > for of > for in

Here are the test cases:

// Test case
    const data = new Array(10000000).fill(0);
    console.log('----- normal for loop -------');
    console.time('for');
    const result_1 = [];
    for (let i = 0; i < data.length; i++) {
        result_1.push(data[i]);
    }
    console.timeEnd('for');
    console.log('----- completed -------');


    console.log('-----for loop -------');
    console.time('for_of');
    const result_2 = [];
    for (let item of data) {
        result_2.push(item);
    }
    console.timeEnd('for_of');
    console.log('----- completed -------');


    console.log('-----for in-------');
    console.time('for_in');
    const result_3 = [];
    for (let key in data) {
        result_3.push(data[key]);
    }
    console.timeEnd('for_in');
    console.log('----- completed -------');


    console.log('-----forEach-------');
    console.time('forEach');
    const result_4 = [];
    data.forEach((item) = > {
        result_4.push(item);
    });
    console.timeEnd('forEach');
    console.log('----- completed -------');


    console.log('-----map-------');
    console.time('map');
    const result_5 = [];
    data.map((item) = > {
        result_5.push(item);
    });
    console.timeEnd('map');
    console.log('----- completed -------');


    console.log('-----while-------');
    console.time('while');
    const result_6 = [];
    let count = 0
    while (data.length > count) {
        result_6.push(data[count]);
        count++
    }
    console.timeEnd('while');
    console.log('----- completed -------');
Copy the code

An array traversal method

every()

Used to test whether all elements in an array pass a test for a given function. It returns a Boolean value. Grammar:

arr.every(callback(element[, index[, array]])[, thisArg])
Copy the code
parameter instructions
callback Callback is a function that tests each element and can take three arguments: Element represents the current value for the test. Index The index of the current value that can be selected for the test. Array is optional. Call the current array of every.
thisArg The this value used when executing callback.

some()

The some() method array is used to determine if at least one element in the array passes the callback function’s test and returns true; The return value is false only if all elements fail the callback test. If you test with an empty array, it returns false in all cases. Grammar:

arr.some(callback(element[, index[, array]])[, thisArg])
Copy the code
parameter instructions
callback Callback is a function that executes on each item of the array and takes three arguments: Element, the element in the array that is currently being processed. Index Optional index of the element being processed in the array. Array Optional, some() is the array to be called.
thisArg The this value used when executing callback.

filter()

The filter() method creates a new array containing all the elements of the test implemented through the provided function. If no array elements pass the test, an empty array is returned. Grammar:

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
Copy the code
parameter instructions
callback Callback is a function that tests each element of an array. Return true to indicate that the element has passed the test and is retained. Return false to indicate that the element is not retained. It takes three arguments: Element, the element in the array that is currently being processed. Index Optional index of the element being processed in the array. Array (optional) Calls the array itself of filter.
thisArg The this value used when executing callback.

forEach()

The forEach() method performs a callback forEach valid item in the array in ascending order, and those deleted or uninitialized items are skipped (for example, on a sparse array). Return value undefined. Grammar:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
Copy the code
parameter instructions
callback Callback is a function that executes on each item of the array and takes three arguments: currentValue, the element in the array that is currently being processed. Index Optional index of the element being processed in the array. Array The array itself is optional.
thisArg The this value used when executing callback.

map()

The map() method creates a new array with the result that each element in the array is the return value from a call to the provided function. Grammar:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])
Copy the code
parameter instructions
callback Callback is a function that generates a new array element, taking three arguments: currentValue, the element in the array that is currently being processed. Index Optional, the index of the current element being processed in the callback array. Array Optional array called by the map method.
thisArg The this value used when executing callback.

reduce()

The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value. Grammar:

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code

Parameter Description:

  • Callback: Callback is a function that executes each value in the array (except for the first value if no initialValue is provided). An accumulator is an accumulator that returns the callback value. It is the cumulative value, or initialValue, returned when the callback was last called. CurrentValue, the element being processed in the array. Index Optional. Index of the current element being processed in the array. If initialValue is provided, the starting index is 0, otherwise it starts from index 1. Array Optional array to call reduce().
  • InitialValue Optional: The value of the first argument when the callback function is first called. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.

reduceRight()

The reduceRight() method takes a function as an accumulator and reduces each value of the array (from right to left) to a single value. Grammar:

arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code

Parameter Description:

  • Callback: Callback is a function that executes each value in the array (except for the first value if no initialValue is provided). An accumulator is an accumulator that returns the callback value. It is the cumulative value, or initialValue, returned when the callback was last called. CurrentValue, the element being processed in the array. Index Optional. Index of the current element being processed in the array. If initialValue is provided, the starting index is 0, otherwise it starts from index 1. Array Optional, call the array of reduceRight().
  • InitialValue Optional: The value of the accumulator when the callback function is called for the first time. If the initial value is not provided, the last element in the array is used and skipped. If no initial value is given, ensure that the array is not empty.

Otherwise, calling reduce or reduceRight on an empty array without providing an initial value (e.g. [].reduce((ACC, cur, IDx, arr) => {})) will result in TypeError: Reduce of empty array with no initial value.

Array lookup

1.find()

The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined. Grammar:

arr.find(callback[, thisArg])
Copy the code
parameter instructions
callback Callback is a function that executes on each item of the array and takes three arguments: Element, the element in the array that is currently being processed. Index Optional index of the element being processed in the array. Array The array itself is optional.
thisArg The this value used when executing callback.

2.findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided test function. Returns -1 if no corresponding element is found. Grammar:

arr.findIndex(callback[, thisArg])
Copy the code
parameter instructions
callback Callback is executed for each element in the array, automatically passing in three arguments: Element, the current element. Index, the index of the current element. Array Optional, call an array of findIndex.
thisArg Optional. Callback is executed as the value of this object.

You can modify operations on the original array

1.fill()

The fill() method fills all elements of an array from the start index to the end index with a fixed value. Does not include terminating indexes. And returns the modified array. Grammar:

arr.fill(value[, start[, end]])
Copy the code

Start and end are optional. Default values are 0 and the value of the length attribute of this object, respectively.

  • Value: The value used to populate an array element.
  • Start: Optional. Start index. Default value is 0. If start is negative, the start index is automatically computed to length

+ start, where length is the value of the length property of this. If end is negative, the end index is automatically evaluated as length+end.

  • End: Optional. Terminates the index. Default is this.length.

Example:

[1.2.3].fill(4);               / / (4, 4, 4]
[1.2.3].fill(4.1);            / / [1, 4, 4]
[1.2.3].fill(4.1.2);         / / [1, 4, 3)
[1.2.3].fill(4.1.1);         / / [1, 2, 3]
[1.2.3].fill(4.3.3);         / / [1, 2, 3]
[1.2.3].fill(4, -3, -2);       / / [4, 2, 3]
[1.2.3].fill(4.NaN.NaN);     / / [1, 2, 3]
[1.2.3].fill(4.3.5);         / / [1, 2, 3]
Array(3).fill(4);                / / (4, 4, 4]
[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}

// Objects by reference.
var arr = Array(3).fill({}) / / / {}, {}, {};
// Note that if fill takes a reference type, it will result in a single reference type being executed
// 如 arr[0] === arr[1] 为true
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
Copy the code

2.push()

The push() method adds one or more elements to the end of an array and returns the array’s new length. Grammar:

arr.push(element1, ... , elementN)Copy the code

Parameter Description:

  • ElementN: The element added to the end of the array.

3.pop()

The pop() method removes the last element from the array and returns the value of that element. This method changes the length of the array (returning undefined if the array is empty). Grammar:

arr.pop()
Copy the code

4.reverse()

The reverse() method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array. Grammar:

arr.reverse()
Copy the code

5.shift()

The shift() method removes the first element from the array and returns its value (undefined if the array is empty). This method changes the length of the array. Grammar:

arr.shift()
Copy the code

6.unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array (this method modifies the original array). Grammar:

arr.unshift()
Copy the code

7.splice()

The splice() method modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array (an array of deleted elements). If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned. . This method changes the original array. Grammar:

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Copy the code

parameter

  • Start Specifies the starting position of the modification (counting from 0). If the length of the array is exceeded, the contents are appended from the end of the array. If it is negative, it represents the number of bits from the end of the array (counting from -1, which means -n is the NTH element to the last and equivalent to array.length-n); If the absolute value of a negative number is greater than the length of the array, the starting position is bit 0.
  • DeleteCount This parameter is optional and is an integer that indicates the number of array elements to be removed. If deleteCount is greater than the total number of elements after start, all elements after start are deleted (including the start bit). If deleteCount is omitted, or its value is greater than or equal to array.length-start (that is, if it is greater than or equal to the number of all elements after start), then all elements in the array after start are deleted. If deleteCount is 0 or negative, the element is not removed. In this case, at least one new element should be added.
  • item1, item2, … Optional, the element to be added to the array, starting at the start position. If not specified, splice() will delete only array elements.

8.sort()

The sort() method sorts the elements of an array using an in-place algorithm and returns the array. The default sort order is the syntax built when converting elements to strings and then comparing their UTF-16 code unit value sequences:

arr.sort([compareFunction])
Copy the code

parameter

  • CompareFunction optional. Used to specify functions that are sorted in a certain order. If omitted, the element is sorted by the Unicode loci of each character in the converted string.

Operations that do not modify the original array

1.concat()

The concat() method is used to merge two or more arrays. This method does not change an existing array, but returns a new array. Grammar:

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
Copy the code

parameter

  • ValueN Optional arrays and/or values that will be merged into a new array. If all valueN arguments are omitted, concat returns a shallow copy of the existing array that called the method.

2.join()

The join() method joins all the elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, that item is returned without a delimiter. Grammar:

arr.join([separator])
Copy the code

parameter

  • Separator Optional, specifies a string to separate each element of the array. Convert the delimiter to a string if necessary. If default, array elements are separated by commas (,). If separator is an empty string (“”), there are no characters between all elements.
var a = ['Wind'.'Rain'.'Fire'];
var myVar1 = a.join();      // myVar1 changes to "Wind,Rain,Fire"
var myVar2 = a.join(', ');  // myVar2 changes to "Wind, Rain, Fire"
var myVar3 = a.join('+'); // myVar3 changes to "Wind + Rain + Fire"
var myVar4 = a.join(' ');    // myVar4 changes to "WindRainFire"

Copy the code

3.slice()

The slice() method returns a new array object that is a shallow copy (including begin, but not end) of the array determined by begin and end. The original array will not be changed. Grammar:

arr.slice([begin[, end]])
Copy the code

parameter

  • Begin (optional) Extracts the original array elements from the index starting from 0. If this parameter is negative, it extracts from the penultimate element of the original array, and slice(-2) extracts from the penultimate element of the original array to the last element, including the last element. If begin is omitted, slice starts at index 0. If BEGIN exceeds the index range of the original array, an empty array is returned.
  • End (optional) extracts the index at the end (starting from 0), and ends the extraction at that index. Slice extracts all elements indexed from begin to end (including begin, but not end). Slice (1,4) extracts all elements (elements indexed 1, 2, and 3) from the second element through the fourth element in the array. If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction. Slice (-2,-1) extracts the penultimate element of the array to the last element (excluding the last element, i.e. only the penultimate element). If end is omitted, slice extracts all the way to the end of the original array. If end is greater than the length of the array, Slice will extract all the way to the end of the array.

4.toString()

ToString () returns a string representing the specified array and its elements. Grammar:

arr.toString()
Copy the code

Array flattening [1, 2, [3, [4, 5]] => [1, 2, 3, 4, 5]

  1. Flat method

arr.flat(Infinity)
Copy the code
  1. Traversal, recursive methods

/ / use the reduce
function flatten(arr) {
    return arr.reduce((pre, current) = > {
        return pre.concat(Array.isArray(current) ? flatten(current) : current)
    }, [])
}

// forEach
function flatten(arr) {
    let result = []
    arr.forEach(item= > {
        if(Array.isArray(item)) {
            result = result.concat(flatten(item))
        } else {
            result.push(item)
        }
    })
    return result
}

Copy the code
  1. Use toString and split
function flatten(arr) {
    The toString method concatenates arrays and returns a string containing each array element separated by commas.
    //split returns an Array of the source string separated by the position where the separator appears
    return arr.toString().split(', ').map(item= > Number(item))
}
Copy the code
  1. Use join and split
function flatten(arr) {
    The //join() method returns an array as a string, split with a comma by default
    //split returns an Array of the source string separated by the position where the separator appears
    return arr.join(', ').split(', ').map(item= > Number(item))
}
Copy the code

The attributes of an object in an array element are de-duplicated


let arr = [
    {"age": 13."name": "s"},
    {"age": 14."name": "sss"},
    {"age": 14."name": "sddd"},
    {"age": 25."name": "saaaa"},]// Use the attributes of the object to de-weigh
function getData(arr) {
    let result = [], ob = {}
    arr.forEach(item= > {
        if(! ob[item.age]) { result.push(item) ob[item.age] =true}})return result
}

let res = getData(arr) // [{"age":13,"name":"s"},{"age":14,"name":"sss"},{"age":25,"name":"saaaa"}]

Copy the code

Copy the array

  1. Deep copy implementation
// Simple version
function deepClone(val) {
    if(typeof val === "object"&& val ! = =null) {let result = Array.isArray(val)? [] : {}
        for(let key in val) {
            result[key] = deepClone(val[key])
        }
        return result
    }
    return val
}
Copy the code
  1. Extend operator implementation
let arr = [
    {"age": 13."name": "s"},
    {"age": 14."name": "sss"},
    {"age": 25."name": "saaaa"},];let arr1 = [...arr]
arr1[0] = true    
console.log(arr1);
/ / /
// true,
// {"age": 14, "name": "sss"},
// {"age": 25, "name": "saaaa"},
// ]
Copy the code

An array of overlap

Use Filter and includes

let arr1 = [1.2.3.3.4.5]
let arr2 = [3.4.6.7]
let arr3 = [...new Set(arr1)].filter(item= > arr2.includes(item))   / / [3, 4]
Copy the code

Various operations when array elements are objects

const arr1 = [
    { id: '11'},
    { id: '12'}, 
    { id: '13'}];const arr2 = [
    { id: '12'},
    { id: '13'}, 
    { id: '14'}];Copy the code
  1. Array intersection (For a given set, returns a new set containing elements in both sets.)
function intersection(arr1, arr2) {
    return arr1.filter(item= > arr2.some(item2= > item2.id === item.id))
}
let result = intersection(arr1, arr2)   //[{ id: '12'},{ id: '13'}]
Copy the code
  1. Array difference set (For a given set of two sets, return a new set containing all elements that exist in the first set and not in the second set.)
function difference(arr1, arr2) {
    return arr1.filter(item= > arr2.every(item2= >item2.id ! == item.id)) }let result = difference(arr1, arr2)   //[{ id: '11'}]
Copy the code
  1. Array union (For a given set of two sets, return a new set containing all the elements of both sets.)
function getUnion(arr1, arr2) {
    let newArr = arr1.concat(arr2)
    let result = []
    let obj = {}
    newArr.forEach(item= > {
        if(! obj[item.id]) { result.push(item) obj[item.id] =true
        }
    })
    obj = null
    return result
}

let result = getUnion(arr1, arr2)
Copy the code