In this article, we’ll look at 34 common methods for arrays

  • I categorize these methods according to my own concerns (e.g., sort(), reverse() and find(), findIndex() definitely iterate internally, but I’ve grouped them into sort and position-dependent categories)
  • Each example is accompanied by code and a screenshot of the results of the latest version of Chrome running

Tip: This article is explained from the right to the left

Fuck!!


1. Form conversion

1.1 the join ()

  • Function: Converts an array to a string
  • Use commas as separators by default
let arr = [1, 2, 3]; arr.join(); / / "1, 2, 3"Copy the code
  • If you want to separate each item in the array with another symbol (such as -)
let arr = [1, 2, 3]; arr.join('-'); / / "1-2-3"Copy the code

1.2 the toString ()

  • Function: Converts an array to a string
let arr = [1, 2, 3]; arr.toString(); / / "1, 2, 3"Copy the code

1.3 toLocaleString ()

  • Function: Converts an array to a string
let arr = [1, 2, 3]; arr.toLocaleString(); / / "1, 2, 3"Copy the code

ToLocaleString () and toString() look the same. What’s the difference?

These two methods are inherited from objects, so all objects can use them, and arrays use them identically. What I want to talk about today is how these two methods differ when used in other scenarios.

  • What difference does it make when a three-digit number uses these two methods
let b = 123;
b.toString(); // "123"
b.toLocaleString(); "123"
Copy the code

  • ToLocaleString () implements the thousandth plus comma effect when the two methods are used for more than three digits
let b = 1234567890; b.toLocaleString(); / / "1234567890" b.t oString (); / / "1234567890"Copy the code

  • When converting a date format, toLocaleString() returns a formatted date, and toString() returns a standard format time
let date = new Date();
date.toLocaleStrin();
date.toString();
Copy the code

1.4 the from ()

1, function: to convert an array-like object or traversable object into a real array

1: Convert an array-like object to a real Array

What is a class array?

ArrayLike in the following code is an array of classes

Let arrayLike = {0: 'apple', 1: '100', 2: 'female' and 3: [' Jane ', 'John', 'Mary'], 'length: 4}Copy the code
  • If the key in the class array is not a number, return an array with the value of length undefined
Let arrayLike = {' name ':' apple ', 'age', '100', 'sex' : 'female' and 'friends' : [' Jane', 'John', 'Mary'], 'length' : 4 } let arr = Array.from(arrayLike); // [undefined, undefined, undefined, undefined, undefined]Copy the code

  • The keys in an array of classes are strings of numbers, the same as those returned by an array of classes whose keys are numbers
Let arrayLike = {' 0 ':' apple ', '1', '100', '2', 'female' and '3' : [' Jane ', 'John', 'Mary'], 'length' : 4 } let arr = Array.from(arrayLike);Copy the code

  • Returns an empty array with no length property
Let arrayLike = {0: 'apple', 1: '100', 2: 'female ', 3: [' Jane ',' John ','Mary']} let arr = array. from(arrayLike); / / []Copy the code

So you get the characteristics of the class array

  • Class array objects must have a length attribute, which specifies the length of the array. If there is no length attribute, the transformed array is an empty array.
  • The property name of this array object must be a numeric or string number

3, Array.from() 2: Convert a Set of data into a real Array

3. Array.from() takes a second argument, similar to the map method of arrays, which processes each element and places the value in the returned Array

Let arr =,45,97,9797,564,134,45642 [12]; let set = new Set(arr); Array.from(set, item => item + 1);Copy the code

4: Convert a string to an Array

let str = 'hello world! '; Array.from(str);Copy the code

If the argument is a real array, return the array itself

Array.from([12, 45, 47, 56, 213, 4654, 154]);
Copy the code

1.5 of ()

  • Function: Converts one or more values to an array

When we use new Array() to construct an Array, we are ambivalent.

When constructed, you pass in a parameter that indicates how large an array to generate.

Construct by passing multiple arguments, each of which is an element of the array.

  • The array.of () method, on the other hand, has only one meaning, and the argument to of is the element of the transformed Array

1.6 flat ()

Other methods for flattening arrays

  • Returns recursively traversing the array at a specified depth and merging all elements with the elements in the traversed subarray into a new array

  • This method returns a new array with no effect on the original data

  • Parameter: Specifies the structural depth to extract the nested array, default is 1

  • There is no parameter

const arr1 = [0, 1, 2, [3, 4]];
arr1.flat();
Copy the code

  • When there are arguments, flat() takes 2, indicating that the two layers of nested arrays are to be flattened
Const arr2 = [0, 1, 2, [[[3,4]];Copy the code

  • No matter how many layers are nested, it is converted to a one-dimensional array, using the Infinity keyword as an argument.
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
Copy the code

  • If the array is empty, the flat() method skips the empty
var arr4 = [1 2, 3, 4];
arr4.flat();
Copy the code

1.7 flatMap ()

  • Executing a function on each member of the original Array is equivalent to array.prototype.map () and then flat() on the Array of returned values
  • Returns a new array, leaving the original array unchanged
  • Only one layer of the array can be expanded
[2, 3, 4].flatMap((x) => [x, x*2])
Copy the code


2. Stack and queue methods

2.1 push ()

  • Add elements to the end of the array

2.2 pop ()

  • Deletes the last element of the array

2.3 the shift ()

  • Deletes the first element of the array

2.4 the unshift ()

  • Appends the element at the first position in the array

What is the difference between the return value of an add method and a delete method?

  • The element addition methods push() and unshift() return the length of the new array after the element is added
  • The methods pop() and shift() for removing elements return the deleted element

3 sort

3.1 the sort ()

  • Sort numbers
Let arr =,37,32,24,5,101 [1]; arr.sort();Copy the code

  • Alphabetical sort
var arr = ["a", "b", "A", "B"];
arr.sort();
Copy the code

Bart, not as expected, but sort()

  • The default is alphabetical ascending
  • The optional argument to sort() determines the sort order and must be a function
  • Without arguments, the elements in the array are sorted in ASCII character order

If you want the sort you want, you can pass in a comparison function in sort()

As described in the documentation, the code is as follows:

let arr = [1, 37, 32, 24, 5, 101];
   function compare(val1, val2) {
       if (val1 < val2) {
           return -1;
       } else if (val1 > val2) {
           return 1;
       } else {
           return 0;
       }
   }
arr.sort(compare);
Copy the code

  • More commonly written:
let arr = [1, 37, 32, 24, 5, 101];
arr.sort(function(x, y){
    return x - y;
});
Copy the code

When we use sort() on an array, we pass the elements of the array item by item to compare as arguments…

3.2 reverse ()

  • Reverses the order of the elements in an array
var arr = [1, 5, 24, 32, 37, 101];
arr.reverse();
Copy the code


4 splice

4.1 the concat ()

  • Joins two or more arrays
  • This method does not alter the existing array, but simply returns a copy of the concatenated array
Var arr = [1,3, 5, 7]; var arrCopy = arr.concat(9, [11, 13]);Copy the code

  • As you can see from the above test results, if you pass in an array instead of an array, you simply append the parameters to the array.
  • If an array is passed in, the items from the array are added to the array. But what if you pass in a two-dimensional array?
var arr = [1, 3, 5, 7];
var arrCopy2 = arr.concat([9, [[11, 13]]);
Copy the code

9 is flattened into the outer array, leaving the inner array [11,13]


5 Create a subarray

5.1 slice ()

  • Returns a new array of selected elements from an existing array
  • When there is one argument, the slice() method returns all items from the position specified by the argument to the end of the current array
  • When there are two arguments, the method returns the items between the start and end positions, but not the items at the end position
  • Do not change the original array

  • An argument, creating a subarray from this argument to the last item (from 3 to the last item)
var arr = [1, 3, 5, 7, 9, 11];
var arrCopy1 = arr.slice(1);
Copy the code

  • With two arguments, the subarray created does not include the end parameter
Var arr =,3,5,7,9,11 [1]; var arrCopy1 = arr.slice(1, 4);Copy the code

  • There are two arguments, and both arguments are negative (negative means look up from back)
Var arr =,3,5,7,9,11 [1]; var arrCopy1 = arr.slice(-4 -1);Copy the code


6 when

6.1 splice ()

I think it’s a very, very strong way to delete, insert and replace

1. Delete function

  • Deletes the element and returns the deleted element
  • Changed the original array
  • You can delete any number of items by specifying two parameters: the location of the first item to delete and the number of items to delete.
Var arr =,3,5,7,9,11 [1]; var arrRemoved = arr.splice(0, 2);Copy the code

2. Insert function

  • Inserts an element at the specified index
  • Three arguments are provided: the starting position, 0 (number of items to delete), and the item to insert
var array1 = [22, 3, 31, 12];
array1.splice(1, 0, 12, 35);
Copy the code

3. Replacement function

  • Replaces the element at the specified index position
  • You can insert any number of items into the specified location and delete any number of items at the same time, specifying 3 arguments:
  • The starting position, the number of items to delete, and any number of items to insert.
  • The number of inserted items need not be equal to the number of deleted items.
var array1 = [22, 3, 31, 12];
array1.splice(1, 1, 8);
Copy the code


7 Position correlation

7.1 indexOf ()

  • Returns the position at which a specified string value first appears in a string
  • The second parameter is optional and indicates where the search begins

var arr = [1, 3, 5, 7, 7, 5, 3, 1]; arr.indexOf(5); arr.indexOf(5, 2); Arr.indexof (5, 3); arr.indexof (5, 3); // returns the subscript 5 of 5 after 5Copy the code

7.2 lastIndexOf ()

The indexOf() argument returns the last position of a specified string value, searched from back to front at the specified position in a string

var arr = [1, 3, 5, 7, 7, 5, 3, 1]; arr.lastIndexOf(5); Arr. LastIndexOf (5, 4); arr. LastIndexOf (5, 4) // returns the first occurrence of the element 5 at subscript 2Copy the code

7.3 the find ()

  • Returns the first element in the array that meets the test function criteria, otherwise undefined
  • parameter

var arr = [1, 3, 5, 7, 9, 11];
arr.find((value, index, arr) => {
	return value > 5;
});
Copy the code

  • The callback should return true if the given element satisfies the condition you defined

7.4 fiindIndex ()

  • Returns the index of the first element in the array that meets the test function criteria, otherwise undefined
  • parameter

var arr = [1, 3, 5, 7, 9, 11];
arr.findIndex((value, index, arr) => {
	return value > 5;
});
Copy the code

Similarities and differences?

  • Different: the find() method returns the matched value, while findIndex() returns the index of the matched position.
  • Same: the find() and findIndex() methods both stop the search the first time the callback returns true.

8 merge

8.1 the reduce ()

  • Function:

  • parameter

Var values = [1,2,3,4,5]; var sum = values.reduceRight(function(prev, cur, index, array){ return prev + cur; }, 10); Console. log(sum); // The array starts with an initial value of 10.Copy the code

Why use reduce() when a for loop or forEach can do something that reduce() can do? There are many roads to success, but there is always one that is the shortest, or perhaps reduce() more…

This article addresses only the most common summation uses of reduce(). For the extended use of reduce(), see advanced use of initialVlue, summation, multiplicative, array de-duplication, array flattening, counting the number of occurrences of each element in an array


8.2 reduceRight ()

  • The function of the reduceRight() method is the same as that of reduce(), except that reduceRight() adds the items in the array forward from the end of the array.
  • If the initialValue argument is provided when you call reduceRight(), accumulator is equal to initialValue and currentValue is equal to the last value in the array. If no initialValue argument is provided, prevValue is equal to the last value in the array, and currentValue is equal to the penultimate value in the array.

9 iteration

9.1 the map ()

  • Method creates a new array by performing a function on each array element
  • Method does not perform functions on array elements that have no value
  • Method does not change the original array
  • parameter

var arr = [1, 2, 3, 4, 5];
var arr2 = arr.map((item) => {
	return item * 2;
});
Copy the code

9.2 the forEach ()

  • Call a function once for each array element (callback function)
  • parameter

var arr = [1, 2, 3, 4, 5];
arr.forEach((item, index, arr) => {
	console.log(item + ' ' + index + ' ' +(a === arr));
});
Copy the code

9.3 the filter ()

  • “Filter” function, each item in the array runs a given function, returns an array that meets the filter criteria.
  • Do not change the original array

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arr2 = arr.filter((item, index) => {
	return item > 8 && index % 3 == 0;
});
Copy the code

9.4 every ()

  • True is returned if all items in the array satisfy the condition.
  • Do not change the original array
  • parameter

var arr = [1, 2, 3, 4, 5]; arr.every((item) => { return item > 0; }): arr.every((item) => { return item > 10; }) :Copy the code

9.5 some ()

  • As long as one of the conditions is met, true is returned.
  • Do not change the original array
  • parameter

var arr = [1, 2, 3, 4, 5]; arr.some((item) => { return item > 4; }): arr.some((item) => { return item > 5; }) :Copy the code

9.6 keys ()

  • Used to iterate over groups of numbers.
  • Returns a traverser object, which can be used for… The of loop iterates over the key names
for(let i of (['a', 'b'].keys()) {
    console.log(i);
}
Copy the code

9.7 values ()

  • Used to iterate over groups of numbers
  • Returns a traverser object, which can be used for… The of loop iterates over the key values
for(let i of (['a', 'b'].values()) {
    console.log(i);
}
Copy the code

9.8 entries ()

  • Used to iterate over groups of numbers
  • Returns a traverser object, which can be used for… The of loop iterates over key and value pairs
for(let item of (['a', 'b'].entries()) {
    console.log(item);
}
Copy the code

Call the next method of the traverser object

In generator, you can use next() to get the return value. For generator, see Generator


Ten other

10.1 isArray ()

  • Returns a traverser object, which can be used for… The of loop iterates over the key names
  • Checks whether an object is an array, returning true if it is, and false otherwise
Array. IsArray ([1, 2, 3]); Array.isArray(0); Array.isArray(true); Array.isArray('123');Copy the code

10.2 the fill ()

  • Used to replace an element of an array with a fixed value
  • parameter

  • One parameter
Let arr = [1, 2, 3, 'cc', 5]; arr.fill(1);Copy the code

  • With two parameters
Let arr = [1, 2, 3, 'cc', 5]; Arr. The fill (1, 3);Copy the code

  • Three parameter time
Let arr = [1, 2, 3, 'cc', 5]; let arr = [1, 2, 3, 'cc', 5]; Arr. Fill (1,2,4);Copy the code

10.3 copyWIthin ()

  • Copies elements from a specified location in an array to another specified location in the array.
  • Inside the current array, copies the member at the specified location to another location (overwriting the original member), and returns the current array. That is, using this method, you modify the current array.
  • parameter

  • Two parameters
[1, 2, 3, 4, 5]. CopyWithin (0, 3);Copy the code

  • Three parameters
[1, 2, 3, 4, 5]. CopyWithin (0, 3, 4);Copy the code

CopyWithin (0, -2, -1);Copy the code

10.4 includes ()

  • Checks whether an array contains a specified value, returning true if so, false otherwise.
  • parameter

Returns true if the element is found, false otherwise

[1, 2, 3].includes(2);
[1, 2, 3].includes(4);
[1, 2, 3].includes(3, 3);
[1, 2, 3].includes(3, -1);
Copy the code

Includes and indexOf()?

We usually use indexOf() to determine if an array contains an element. However, indexOf has two minor drawbacks:

  • It’s not semantic enough. It returns the first occurrence of the element, and -1 if it can’t be found, usually compared to -1.
  • Internal use of the strict equality operator (===) in indexOf() causes NaN errors, and NaN cannot be found if it exists in the array.
NaN === NaN lett arr = [NaN, 8, "hello"]; arr.indexOf(NaN); // NaN is in arr, but no result is returned arr.includes(NaN);Copy the code


The arrangement is in a hurry, if there is a mistake, welcome to point out.

Quote 1 quote 2 quote 3


I am Yangyang Li, a front-end brick moving younger brother

Ten thousand years is too long, seize the day, see you next time