Array creation

  • Common methods:

    / / literal
    var arr = [1.2.3]; / / [1, 2, 3]
    // Construct
    var arr = Array(a);/ / []
    var arr = Array(1.2.3); / / [1, 2, 3]
    var arr = Array(3); / / /,,
    Copy the code

In general, new Array === Array, so it doesn’t really matter whether you add new or not.

  • New methods in ES6:

    • Array.of() returns an Array of arguments
    let arr = Array.of(1.2.3); / / [1, 2, 3]
    Copy the code
    • Array.from() converts the argument object to an Array, not changing the original object, but returning a new Array object

      Object requirements:

      1. Has the length property
      2. Iterable, that is, must have the [symbol. iterator] interface data type structure such as: Set, Map,NodeList, string, etc

      Parameters:

      1. (Required) Object to be converted to an array.
      2. (Optional) Similar to the Map method, each element is processed and placed in a new array that is returned
      3. (Optional) used to bind the this pointer when the second parameter method is executed.
    let a = {0: '1'.1: '2'.2: '3'.'length': 3};
    let arr = Array.from(a); / / [' 1 ', '2', '3']
    / / string
    let arr = Array.from('array'); //['a','r','r','a','y']
    / / Set, and the Map
    let arrset = Array.from(new Set(['func'.window])); //['func', window]
    let arrMap = Array.from(new Map([1.2], [3.4], [5.6])); / / [[1, 2], [3, 4], [5, 6]]
    // The use of class map methods
    let theArr = Array.from([1.2.3], x => ++x); / / / 2 and 4
    Copy the code

Array methods:

There are a variety of methods of array, I will explain one by one through examples and other scenarios for you to apply:

Splice () add/remove/replace [change the array]

arr.splice(index, num, item1, item2, …) ;

Parameter Description:

  1. Index (required): An integer to specify where to add/remove elements. Negative numbers can be used to count from the end.
  2. Num (Optional): indicates the number of elements to be deleted. If you do not want to delete the element, set this parameter to 0.
  3. item1,item2…. (Optional): Elements added to the array.

Return value: In the case of a delete operation, the deleted element is returned in a new array.

Usage Scenarios:

  • Delete element:
let arr = [1.2.3.4.5];
// Delete the first three elements of arR
let before = arr.splice(0.3); / / [1, 2, 3]
// arr = [4,5]
// Remove the last element of arr
let after = arr.splice(- 1.1); //[5], note that there is only one element after the last bit, and no matter how large the last bit is written, only the last element will be deleted and returned
// ArR = [4]
Copy the code
  • Add elements:
let arr = [1.2.3.4.5];
let addFromStart = arr.splice(0.0.0); // [] is not deleted, so an empty array is returned
console.log(arr); / /,1,2,3,4,5 [0]
let addFromEnd = arr.splice(- 1.0.6); / / []
console.log(arr); / /,1,2,3,4,6,5 [0]!!!!!! Notice that the element is added forward from the last digit, so 6 comes before 5.
Copy the code
  • Delete and add
let arr = [1.2.3.4.5];
let arrAddAndDelete = arr.splice(0.2.100); / / [1, 2]
console.log(arr); / / 5-tetrafluorobenzoic [100]
Copy the code

Features:

1. The elements of the operation will include the starting element.

2. If there are not enough elements in the array, it will be deleted until the last array.

Pop () removes the last element of the array

arr.pop();

There is no parameter

Return value: deleted element

Usage Scenarios:

let arr = [1.2.3];
let deleteItem = arr.pop(); / / 3
console.log(arr); / / [1, 2]
Copy the code

Shift () deletes the first element of the array

arr.shift();

There is no parameter

Return value: deleted element

Usage Scenarios:

let arr = [1.2.3];
let deleteItem = arr.shift(); / / 1
console.log(arr); / / [2, 3]
Copy the code

Push () adds elements to the end

arr.push(item1,item2, item3,…) ;

Arguments: Elements added to the end of the array

Return value: The length of the array after addition

Usage Scenarios:

let a = [1.2.3];
let theLength = a.push(4); / / 4
console.log(a); / / [1, 2, 3, 4]
Copy the code

Unshift () adds elements to the beginning of the array

arr.unshift(item1,item2,…) ;

Parameter: Element added to the beginning of the array

Return value: The length of the array after addition

Usage Scenarios:

let a = [1.2.3];
let theLength = a.unshift(0); / / 4
console.log(a); / /,1,2,3 [0]
Copy the code

Sort () array sort

arr.sort(func)

Sort the array and return the array

Parameter: comparison function specifying sort order (optional)

Arguments passed to the function: two default arguments, except the two elements to be compared (indicated by a and b), and the sorting order is mainly related to the return value of the function. If the return value is less than 0, a precedes B. If the return value is 0, a and B remain the same; If the return value is greater than 0, b precedes A.

Return value: sorted array

Usage Scenarios:

  • By default, if no arguments are passed, the default is alphabetical ascending. If it is not a string, toString() is called to convert the element toString Unicode before string comparison. So the default sort() is not suitable for comparing numbers and so on.

    let arr = ["A"."C"."B"."E"."D"];
    arr.sort();
    console.log(arr); //["A","B","C","E","D"]
    Copy the code
  • Sort an array in ascending and descending order

    let arr = [9.15.35.21.42.2.7];
    If a < b, then a-b is less than 0, and a is before B
    arr.sort((a,b) = > a-b);
    console.log(arr); //[2, 7, 9, 15, 21, 35, 42]
    // if a < b, then b-a is greater than 0 and a is after B
    arr.sort((a,b) = > b-a);
    console.log(arr); // [42, 35, 21, 15, 9, 7, 2]
    Copy the code
  • Complex condition (custom) judgment

    // In order of age, women (sex = 0) are ranked before men (sex = 1) if they are the same age.
    let arr = [{age: 18.sex: 0}, {age: 19.sex: 0}, {age: 20.sex: 0}, {age: 18.sex: 1}, {age: 19.sex: 1}];
    arr.sort((a,b) = > {
      if (a.age === b.age) { // If they are of the same age, they are arranged according to gender, female first
        return a.sex - b.sex;
      } else { // If the age is different, the default is ascending by age
        returna.age - b.age; }})console.log(arr); //[{age: 18, sex: 0}, {age: 18, sex: 1}, {age: 29, sex: 0}, {age: 19, sex: 1}, {age: 20, sex: 0}];
    Copy the code

Reverse () array reversal

arr.reverse();

There is no parameter

There is no return value

Usage Scenarios:

let arr = [1.2.3];
arr.reverse();
console.log(arr); [3.2.1]
Copy the code

CopyWithin () array at the specified location

arr.copyWithin(index, start, end)

Parameters:

  1. Index (required): The position at which the element is replaced, with a negative value indicating that it starts later.
  2. Start (Optional): reads data from this location. The default value is 0, and negative values indicate that data is searched from behind.
  3. End (optional): Stops reading at this point. Default is the length of the array, with a negative value indicating that it starts at the end, but actually copies the element before it.

There is no return value

Usage Scenarios:

let arr = [1.2.3.4.5];
arr.copyWithin(0.2.4); // Copy some elements and replace some elements
console.log(arr); / /,4,3,4,5 [3]
Copy the code

Fill () array [change the original array, ES6]

arr.fill(value, start, end)

Parameters:

  1. Value (required): The value to populate.
  2. Start (Optional): start position for filling. The default value is 0.
  3. End (Optional) : The end of the fill. Default is the length of the array.

There is no return value

Usage Scenarios:

let arr = new Array(3);
arr.fill(1);
console.log(arr); / /,1,1 [1]
arr.fill(2.1.3);
console.log(arr); / /,2,2 [1]
Copy the code

Slice () copies array elements without changing the original array

arr.slice(start, end);

Parameters:

  1. Start (Optional): indicates the index position to start replication. Negative values indicate forward from the tail. The default value is 0.
  2. End (Optional): Index position to end the copy, copied to the element before it, negative value from tail forward, default array length.

Return value: new array copied

Usage Scenarios:

  • Copy simple data types

    let a = [1.2.3];
    let b = a.slice(0.2);
    console.log(a,b); / / [1, 2, 3] [1, 2]
    // Shallow copy, which copies simple data types without interfering with each other.
    a[0] = 100;
    console.log(a,b); // [100, 2, 3] [1, 2]
    b[0] = 200;
    console.log(a,b); // [100, 2, 3] [200, 2]
    Copy the code
  • Copy complex reference types

    let a = [{id:1.num:5}];
    let b = a.slice();
    console.log(a,b); //[{id:1,num:5}] [{id:1,num:5}]
    // Shallow copy, which copies complex reference types and then interferes with each other. Because copying only points to an object, not a copy.
    a[0].id = 2;
    console.log(a,b); //[{id:2,num:5}] [{id:2,num:5}]
    b[0].num++;
    console.log(a,b); //[{id:2,num:6}] [{id:2,num:6}]
    Copy the code

Join () converts an array to a string [without changing the original array]

arr.join(str);

Parameters: STR (optional): Used as the specified delimiter. Default is comma.

Return value: Returns the converted string.

Usage Scenarios:

let a = [1.2.3];
let str = a.join();
console.log(str); / / "1, 2, 3"
let anotherStr = a.join(The '-');
console.log(anotherStr); / / "1-2-3"
Copy the code

Note that the join method defaults to [object object] when the array is an object.

ToString ()/toLocaleString()

arr.toString() / arr.toLocaleString();

There is no parameter

Return value: converted string.

Both are similar to join, except toLocaleString is equivalent to calling toLocaleString methods on array elements before joining them. ToString () concatenates array elements into strings separated by commas.

Usage Scenarios:

let arr = [1.2.3];
let arrStr = arr.toString();
console.log(arrStr); / / "1, 2, 3"
let arrLocale = [new Date(),1.2];
let LocaleStr = arrLocale.toLocaleString();
console.log(LocaleStr); / / "2019/4/16 5:05:43 afternoon, 1, 2"
Copy the code

Concat () joins multiple arrays, returning a new array. [Do not change the original array]

arr.concat(arr1,arr2,arr3);

Parameters: arr1, arR2,arr3: Arrays to be merged, or can be values directly.

Return value: New array after merge.

Usage Scenarios:

let arr = [1.2.3];
let arr1 = [4.5];
let afterArr = arr.concat(arr1);
console.log(afterArr); //[1, 2, 3, 4, 5]
console.log(arr); / / [1, 2, 3]
console.log(arr1); / / [4, 5]
Copy the code

We can also merge arrays using… ES6 provides extended operators to merge

let arr = [1.2.3];
let arr1 = [...arr,4.5]; / / [1, 2, 3, 4, 5]
Copy the code

IndexOf () finds the index value of an element in an array. [Do not change the original array]

arr.indexOf(value, fromIndex);

Parameters:

  1. Value (required) : The value of the element to look up
  2. FromIndex (optional): Searches from here, accepts negative values, 0 by default, and returns -1 if the array length is exceeded.

The return value:

  • If an element is found, the index value of the element is returned.
  • If this element is not present in the array, return -1.

Attention!!!!!! IndexOf uses strict equality (===) and there is no implicit type conversion.

let arr = [1.2.3];
console.log(arr.indexOf(1)); / / 0
console.log(arr.indexOf(1.1)); // -1
console.log(arr.indexOf(4)); // -1
Copy the code

LastIndexOf () finds the last position of the specified element in the array. [Do not change the original array]

arr.lastIndexOf(value, fromIndex);

Parameters:

  1. Value (required): The element to look up
  2. FromIndex (optional) :The reverseThe start of the search, which defaults to array length -1, looks for the entire array.

Return value: the last position of the element.

let arr = [1.2.3.2.1];
console.log(arr.lastIndexOf(1)); / / 4
console.log(arr.lastIndexOf(2)); / / 3
Copy the code

Includes () finds whether the array contains an element. [Do not change the original array, ES7]

arr.includes(value);

Parameters:

  1. Value (required) : The value of the element to look up
  2. FromIndex (optional): Searches from here, accepts negative values, 0 by default, and returns -1 if the array length is exceeded.

Return value: Boolean

Differences from indexOf:

  1. IndexOf is not recognizedNaN, but includes does.
  2. When we only need to find whether it contains, if the returned index may be 0, it is not convenient for us to directly determine some operations.
let arr = [1.NaN.100.The '42'];
console.log(arr.includes(1)); //true
console.log(arr.includes(NaN)); //true
console.log(arr.includes(1.3)); //false
Copy the code

traverse

ForEach iterates through the values in an array in ascending order

arr.forEach(function(value, index, arr), this);

Parameters:

  1. Value (required): Array value of the current traversal.
  2. Index (Optional): indicates the index of the current traversal.
  3. Arr (Optional): The array object itself.
  4. This (optional): when the callback function is executed.

Returned value: None

Some features:

  1. If a deleted element or an empty element is encountered during iteration, the callback function is skipped.
  2. An empty array is not called back.
  3. The number of iterations is confirmed before the loop, that is, adding elements during the loop will not be traversed.
let arr = [1.2.3.4.5 ];
const obj = {name: 'obj'};
arr.forEach(function(value, index,array) {
  arr[4] = 'edited'; // Change the value of the empty element. The value passed to the callback is traversed up to this point
  arr.push(6); // The newly added element will not be traversed.
  console.log(value, index);
  console.log(this.name); // "obj"
}, obj); // use this to point to obj in the callback function
Copy the code

Some () checks if there are elements in the array that satisfy the condition

arr.some(function(value, index, arr), this);

Parameters:

  1. Value (required): Array value of the current traversal.
  2. Index (Optional): indicates the index of the current traversal.
  3. Arr (Optional): The array object itself.
  4. This (optional): when the callback function is executed.

Return value: Boolean type ture or false

let arr = [1.2.3.4.5];
let result1 = arr.some((value) = > value > 6); //false
let result2 = arr.some((value) = > value < 2); //true
Copy the code

Every () checks whether all elements in the array satisfy the condition

arr.some(function(value, index, arr), this);

Parameters:

  1. Value (required): Array value of the current traversal.
  2. Index (Optional): indicates the index of the current traversal.
  3. Arr (Optional): The array object itself.
  4. This (optional): when the callback function is executed.

Return value: Boolean type ture or false

let arr = [1.2.3.4.5];
let result1 = arr.every((value) = > value > 6); //false
let result2 = arr.every((value) = > value < 6); //true
Copy the code

Filter () filters the original array and returns the new array

arr.filter(function(value,index,arr), this);

Parameters:

  1. Value (required): Array value of the current traversal.
  2. Index (Optional): indicates the index of the current traversal.
  3. Arr (Optional): The array object itself.
  4. This (optional): when the callback function is executed.

Return value: new array.

let arr = [1.2.3.4.5];
// Get only the elements greater than 2 in the array and put them in a new array
let result = arr.filter(item= > item > 2);
console.log(result); / / / three, four, five
Copy the code

Map () processes each element in the array, returning the new array

arr.map(function(value, index, arr), this);

Map traversal must have a return value within the callback, be careful.

Parameters:

  1. Value (required): Array value of the current traversal.
  2. Index (Optional): indicates the index of the current traversal.
  3. Arr (Optional): The array object itself.
  4. This (optional): when the callback function is executed.

Return value: new array.

let arr = [1.2.3.4.5];
// The array element is doubled
let result = arr.map(item= > item * 2);
console.log(result); //[2, 4, 6, 8, 10]
Copy the code

Accumulator of the reduce() array, merged into a single value.

arr.reduce((total, value, index, arr), init)

Parameters:

  1. Total (must) : the initial value, followed by the return value of the previous callback.
  2. Value (required): The value of an array element.
  3. Index (Optional): indicates the index value.
  4. Arr (Optional): Array object.
  5. Init (Optional): indicates the initial value.

Return value: the cumulative value.

  • If init is provided when reducing is called, the first time total is init and value is the value of the first element.
  • If init does not provide it, total is the value of the first element of the array and value is the value of the second element.
let arr = [1.2.3.4];
let sum = arr.reduce((total,value) = > total + value ); / / 10
Copy the code

Find ()/findIndex() finds array members by criteria [ES6]

arr.find(function(value, index, arr), this);

Parameters:

  1. Value (required): Array value of the current traversal.
  2. Index (Optional): indicates the index of the current traversal.
  3. Arr (Optional): The array object itself.
  4. This (optional): when the callback function is executed.

Return value: find() returns the first qualified array member, undefined if none exists. FindIndex () returns the index of the eligible array members.

let arr = [1.2.3.4];
let result1 = arr.find((value) = > value > 3); 
console.log(result1);/ / 4
let result2 = arr.findIndex((value) = > value > 3);
console.log(result2); / / 3
Copy the code

Flat () depth traversal unrolled array

arr.flat(depth);

Parameter: depth(Optional): Extract the structure depth of the nested array. The default is 1.

Return value: The expanded array.

let arr = [1.2[3.4[5.6]]]
let one = arr.flat();
console.log(one); // the default value is 1, so only one layer of nesting can be expanded [1,2,3,4,[5,6]]
let two = arr.flat(2);
console.log(two); / / [6]
// If you don't know how many layers are nested, you can use Infinity to expand them all
let inf = arr.flat(Infinity);
console.log(inf); / / [6]
The flat method removes blank items from the array
let arr2 = [1.2.3.5];
console.log(arr2.flat()); / /,2,3,5 [1]
Copy the code

Share an interview question that can be solved by using this question. Through this question, we found that there is a method called Flat: Joy:

Flattening and de-duplicating a multidimensional array produces an ascending array.

let arr = [1.2.3.4.5[2.4.5.8[44.88.1.3.4.8.5.7.6[123].111].15].2.8.7];
let newArr = Array.from(new Set(arr.flat(Infinity))).sort((a,b) = > a - b)
console.log(newArr); //[1, 2, 3, 4, 5, 6, 7, 8, 15, 44, 88, 111, 123]
Copy the code

Keys () traverses key names/values() traverses key values/entries() traverses key value pairs

arr.keys() / arr.values() / arr.entries()

There is no parameter

Return value: an Array Iterator, so we can’t print the object directly, but iterate over it.

let arr = [9.8.7.6.5.4.3.2.1]
for(let index of arr.keys()){
    console.log(index); / / 0,1,2,3,4... In turn, print
}

for(let value of arr.values()){
    console.log(value); / / 9,8,7,6,5... In turn, print
}

for(let [index, value] of arr.entries()){
    console.log(index,value); / / 0 2, 7, 8, 9 1
}
Copy the code

You can also call the traverser manually

let arr =["one"."two"."three"];
let result = arr.entries();
console.log(result.next().value); //[0, "one"]
console.log(result.next().value); //[1,"two"]
console.log(result.next().value); //[2, "three"]
Copy the code

conclusion

When I have been using array methods before, I feel that I can only remember some common ones. Sometimes I need to confirm the documents before I start to use some array methods. Some methods of feeling array still need a systematic understanding, and some more efficient native methods can be applied in the development.

If you have any objection to the content of this article, please feel free to discuss it in the comments section!

Reference links:

MDN

[ECMAScript 6 Getting Started](