preface

Recently with his girlfriend, ahem… Learn the JS array method, in a few words to describe the word is heard, the actual use, encounter the time can not distinguish the specific method will get what result.

Today I will tidy up the method of JS array through this article, let you through this article to master a series of array operations, at the same time, in the interview or work can also write concise, elegant, beautiful, efficient code. Secondly, this is for my girlfriend. Will she cry when she sees it? Will it? Will it? Will it?

Do I have a girlfriend, by the way?

Ah, this, this… Does it matter?

(mobile terminal may not see) to get hd PDF, please reply in the wechat public number [little Lion front Vue]

Read the instructions

To get to the bottom of it, LET me introduce the overall directory structure of this article and give you a rough idea of what I’m going to output.

Obviously, there are many, many methods in the array, but some are rarely used in the actual job or interview process, so I won’t just throw them all out and parse them. So, I will be more important degree of high method as far as possible with detailed concise language belt, at the same time, examples of a few examples, self-test case for you to deepen consolidation.

Secondly, this article will also mention the interview test questions, such as the classic flattening problem, array deduplicate, merge, sort, change the original array method, do not change the original array method, and so on.

Ok, let’s get into the text

Array traversal

Remember this year, the interviewer asked a classic interview question: tell me what you know about the array traversal method?

Friends I think this problem should also be met at the interview, the interviewer asks this question one is your master degree of array method, and the other can go through the way you said to choose one of them continues to depth, such as the reduce, map to use and so on, therefore, I would array traversal, as the first module to explain in detail.

The for loop

let arr = [1.2.3.4.5];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
/ / 1
/ / 2
/ / 3
/ / 4
/ / 5
Copy the code

for.. Of circulation

From the MDN, for… The of statement iterates over the iterable defining the data to iterate over. In short, for… Of goes through value.

let arr = ['Chocolate'.'zhlll'.'lionkk'];

for (let val of arr) {
  console.log(val);
}
// Chocolate
// zhlll
// lionkk
Copy the code

for… In circulation

From the MDN, for… The in statement iterates over the object’s enumerable properties in any order. In short, for… In goes through the key. For an array, the key corresponds to the subindex of the array.

let arr = ['Chocolate'.'zhlll'.'lionkk'];

for (let key in arr) {
  console.log(key);
}
/ / 0
/ / 1
/ / 2
Copy the code

Array. The forEach () method

Let’s start with the syntax:

array.forEach(callback(currentValue, index, arr), thisArg)
Copy the code

Callback: A function that is executed for each element in the array and takes one to three arguments

ThisArg is an optional argument to thisArg, which is operated on by the forEach() method. It is used as this value when the callback function is executed

A simple example:

let arr = ['Chocolate'.'zhlll'.'lionkk'];

arr.forEach(function (cur, index, arr) {
  console.log(cur, index, arr);
})

// Chocolate 0 [ 'Chocolate', 'zhlll', 'lionkk' ]
// zhlll 1 [ 'Chocolate', 'zhlll', 'lionkk' ]
// lionkk 2 [ 'Chocolate', 'zhlll', 'lionkk' ]
Copy the code

From the example above, we know that forEach needs to pass a callback function, and of those three arguments, the last two are optional. How to make the code a little more elegant, and add the last two arguments as needed:

let arr = ['Chocolate'.'zhlll'.'lionkk'];

arr.forEach((cur) = > {
  console.log(cur);
})
// Chocolate
// zhlll
// lionkk
Copy the code

Question, I think you guys have questions about the last thisArg, so let’s explain:

function Foo() {
  this.sum = 0;
  this.cnt = 0;
}
// Add a method called doSth to the prototype
Foo.prototype.doSth = function (arr) {
  arr.forEach(function (cur) {
    this.sum += cur;
    this.cnt++;
  }, this) // this points to the instance object
}

let foo = new Foo();
let arr = [1.2.3];
foo.doSth(arr);

console.log(foo.sum, foo.cnt);
/ / 6 3
6 === (1+2+3) 3 === (1+1+1)
Copy the code

Note: If an arrow function expression is passed as a function argument, the thisArg argument is ignored because the arrow function is lexically bound to the value this.

Therefore, for normal functions, you can think of this as a parameter to solve the inheritance problem, of course, through the arrow function is a good choice!

The map traverse

Definition: Returns a new array, the result of which is that each element in the array is the return value after calling the provided callback function once.

Let’s start with the syntax:

let newArray = array.map(function(currentValue, index, arr), thisArg)
Copy the code

Callback: A function that is executed for each element in the array and takes one to three arguments

ThisArg is an optional argument to the array thisArg is being operated on by the map() method, which is used as this value when the callback function is executed

A simple example:

let arr = ['Chocolate'.'zhlll'.'lionkk'];

let newArr = arr.map(function (cur, index, arr) {
  console.log(cur, index, arr);
  return cur + index;
})
// Chocolate 0 [ 'Chocolate', 'zhlll', 'lionkk' ]
// zhlll 1 [ 'Chocolate', 'zhlll', 'lionkk' ]
// lionkk 2 [ 'Chocolate', 'zhlll', 'lionkk' ]

console.log(newArr)
// [ 'Chocolate0', 'zhlll1', 'lionkk2' ]
Copy the code

Difficult point, I think friends, with the preposed question, there should not be too many problems to understand thisArg this time, take a look at the following example:

function Foo() {
  this.sum = 0;
  this.cnt = 0;
}
// Add a method called doSth to the prototype
Foo.prototype.doSth = function (arr) {
  let newArr = arr.map(function (cur) {
    this.sum += cur;
    this.cnt++;
    return cur + 10;
  }, this) // this points to the instance object
  return newArr;
}

let foo = new Foo();
let arr = [1.2.3];

console.log(foo.doSth(arr)); // [11, 12, 13]
console.log(foo.sum);/ / 6
console.log(foo.cnt);/ / 3
Copy the code

Some small operations ~

let arr = [1.4.9.16];
let res = arr.map(Math.sqrt); // Pass SQRT in Math to get the square root of each element in the array
console.log(res); // [1, 2, 3, 4]
Copy the code

Conclusion:

  • mapDo not modify the original array itself in which it was calledcallbackChange the array at execution time)

When the callback does not return a value, the last value of the new array is undefined

  • thisThe value of PI ends up with respect to PIcallbackThe observability of the function is based on this rule, which isthisPointing to problems
  • mapIt returns a new array

Reduce traversal

Definition: Execute a reducer (ascending) function that you provide for each element in the array to aggregate the results into a single return value.

Let’s start with the syntax:

let res= array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
Copy the code

Callback: A function that is executed for each element in the array and takes one to four arguments

Accumulator currentValue currentValue currentIndex currentIndex array array initialValue is the value of the first parameter in the first callback call. 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.

A simple example:

let arr = [3.5.7.1.2];
let res = arr.reduce(function (acc, cur, index, arr) {
  console.log(acc, cur, index, arr);
  return acc + cur;
}, 0)
// 0 3 0 [3, 5, 7, 1, 2]
// 3 5 1 [3, 5, 7, 1, 2]
// 8 7 2 [3, 5, 7, 1, 2]
// 15 1 3 [3, 5, 7, 1, 2]
// 16 2 4 [3, 5, 7, 1, 2]
console.log(res);
/ / 18
Copy the code

After reading the above code, you may still be masked, how to output so much, combined with the followinggifGIF to understand:

Difficult points, I think small partners for the parameters so much should be a little to see meng, the following with some small operations to show, and provide a little self-test questions to deepen consolidation ~

let arr = [1.2.3.4.5];
let res = arr.reduce((acc, cur) = > {
  return acc + cur;
}, 0)
console.log(res);/ / 15
Copy the code

Self test question: see below output what?

[1.2.3.4].reduce((x, y) = > console.log(x, y));
Copy the code
  • A: 1 2 and 3 3 and 6 4
  • B: 1 2 and 2 3 and 3 4
  • C: 1 undefined and 2 undefined and 3 undefined and 4 undefined
  • D: 1 2 and undefined 3 and undefined 4
The answer

Answer: D

The Reducer function accepts four parameters:

  1. Accumulator (ACC)
  2. Current Value (cur)
  3. Current Index (idx)
  4. Source Array (SRC)

The return value from the Reducer function, which is allocated to the accumulator, is remembered in each iteration of the array and becomes the final single result value.

The reducer function also has an optional parameter, initialValue, which will be used as the first parameter when the callback function is first called. If initialValue is not provided, the first element in the array is used.

In the example above, the first parameter (Accumulator) received by the reduce method is x and the second parameter (Current Value) is y.

On the first call, the accumulator x is 1 and the current value “y” is 2, printing the accumulator and the current values: 1 and 2.

Our callback function in this example does not return any value, just prints the value of the accumulator and the current value. If the function does not return a value, undefined is returned by default. On the next call, the accumulator is undefined and the current value is “3”, so undefined and 3 are printed.

On the fourth call, the callback function still returns no value. The accumulator is undefined again and the current value is “4”. Undefined and 4 are printed.


Conclusion:

  • If the array is empty and not suppliedinitialValueThat will be thrownTypeError
  • If not providedinitialValue.reduceIt starts at index 1callbackMethod, skipping the first index. If you provideinitialValue, starting with index 0.
  • accIs the return value of the passed function, if yesconsole.logReturns the default valueundefined

filter()

Definition: Creates a new array that contains all the elements of the tests implemented by the provided function.

Let’s start with the syntax:

let newArray = array.filter(function(currentValue, index, arr), thisArg)
Copy the code

Callback: A function that is executed for each element in the array and takes one to three arguments

ThisArg (optional) thisArg (optional) thisArg (optional) thisArg (optional) thisArg (optional) thisArg (optional) thisArg (optional) thisArg (optional) thisArg

A simple example:

let arr = [1.2.3.4.5];

let newArr = arr.filter(function (cur, index) {
  console.log(cur, index);
  return cur % 2= =0;
})
/ / 1 0
1 / / 2
2 / / 3
/ 3/4
/ / 5 4
console.log(newArr); // [2, 4]
Copy the code

See the array.foreach () method section above for thisArg.

In simple terms, return the result that satisfies the condition.

every()

Definition: tests whether all elements in an array pass a specified function test that returns a Boolean value.

Let’s start with the syntax:

array.every(function(currentValue, index, arr), thisArg)
Copy the code

Callback: A function that is executed for each element in the array and takes one to three arguments

The index of the current element being processed in the array arr (optional) Every () method operates on the array thisArg is an optional argument that is used as this value when the callback function is executed

let res1 = [1.2.3.4.5].every(function (cur) {
  return cur > 10;
})
console.log(res1); // false

let res2 = [1.2.3.4.5].every(function (cur) {
  return cur >= 1;
})
console.log(res2); // true

Copy the code

See the array.foreach () method section above for thisArg.

In simple terms, it is to return the result of whether or not a particular condition is met, using a Boolean value.

some()

Definition: tests whether at least one element in an array passes the provided function test. It returns a Boolean value

Let’s start with the syntax:

array.some(function(currentValue, index, arr), thisArg)
Copy the code

Callback: A function that is executed for each element in the array and takes one to three arguments

(optional) The index of the current element being processed in the array arr (optional) The array thisArg (optional) that the some() method is operating on is used as this value when executing the callback function

let res1 = [1.2.3.4.5].some(function (cur) {
  return cur > 10;
})
console.log(res1); // false

let res2 = [1.2.3.4.5].some(function (cur) {
  return cur === 1;
})
console.log(res2); // true
Copy the code

See the array.foreach () method section above for thisArg.

In simple terms, return whether there is at least one result that satisfies a particular condition, using a Boolean value.

Find and findIndex

This method was added in the ECMAScript 6 specification and may not exist in some implementations.

Definition:

Find: Returns the value of the first element in the array that satisfies the provided test function. Otherwise, return undefined.

FindIndex: The index of the first element in the array by providing the test function. Otherwise, return -1.

Let’s start with the syntax:

let ele = array.find(function(elemnet, index, arr), thisArg)

let eleIndex = array.findIndex(function(elemnet, index, arr), thisArg)
Copy the code

Callback: A function that is executed for each element in the array and takes one to three arguments

(Optional) The index of the current element being processed in the elemnet array. (Optional) The index of the current element being processed in the elemnet array. (Optional) The array that the find method is operating on

let res1 = [1.2.3.4.5].find(function (cur) {
  return cur > 2;
})
console.log(res1); / / 3

let res2 = [1.2.3.4.5].findIndex(function (cur) {
  return cur > 2;
})
console.log(res2); / / 2
Copy the code

Keys and values and entries

Definition:

  • keys()Method returns a value containing each index key in the arrayArray IteratorObject.
  • values()Method returns a newArray IteratorObject that contains an array of eachThe value of the index
  • entries()Method returns a newArray IteratorObject that contains each object in the arrayKey/value pairs for the index.
arr.keys()
arr.values()
arr.entries()
Copy the code

A simple example:

let arr = ['Chocolate'.'zhlll'.'lionkk'];

let itKeys = arr.keys();
let itVals = arr.values();
let itEntries = arr.entries();

for (let it of itKeys) {
  console.log(it);
}
/ / 0
/ / 1
/ / 2
for (let it of itVals) {
  console.log(it);
}
// Chocolate
// zhlll
// lionkk
for (let it of itEntries) {
  console.log(it);
}
// [ 0, 'Chocolate' ]
// [ 1, 'zhlll' ]
// [ 2, 'lionkk' ]
Copy the code

All right, so that’s pretty much the end of the story about how to iterate through an array, there may be other ways to do it, but there’s always a way to do it, so we’re going to look at ways to change the array.

Change the original array method

As you may know from my previous blog post on Vue data hijacking source analysis, the decorator pattern is used to solve the problem of not being able to handle arrays. One of the things that is mentioned here is that we need to continue to recursively look at the methods that change the original array. So, let’s explore the use of each of them:

sort()

As for why I ranked first, yes, I met in the interview. At that time, I said to the interviewer that I would rank in order from small to large by default. After learning, I found it was not true.

Let’s start with the syntax:

arr.sort([compareFunction])
Copy the code

CompareFunction Optional, used to specify the functions to be sorted in some order. If omitted, the elements are sorted by the Unicode loci of each character in the string to which they are converted.

Otherwise, if compareFunction(a, b) is specified: if compareFunction(a, b) is less than 0, then a is arranged before B; If compareFunction(a, b) is equal to 0, the relative positions of a and b remain the same. If compareFunction(a, b) is greater than 0, b will be arranged before A.

A simple example:

let arr = [1.10.2.5.8.3];

arr.sort(); / / the default
console.log(arr); // [1, 10, 2, 3, 5, 8]

arr.sort((a, b) = > a - b); // Order from smallest to largest
console.log(arr); // [1, 2, 3, 5, 8, 10]

arr.sort((a, b) = > b - a); // Order from largest to smallest
console.log(arr); // [10, 8, 5, 3, 2, 1]
Copy the code

push()

Some operations similar to stack and queue

Note that push() returns the length of the array after success.

let arr = [1.2];
let res = arr.push(100);
console.log(arr); // [1, 2, 100]
console.log(res); / / 3
Copy the code

pop()

Some operations similar to stack and queue

let arr = [1.2.100];
let res = arr.pop();
console.log(arr); // [1, 2]
console.log(res); / / 100
Copy the code

shift()

Some operations similar to stack and queue

let arr = [1.2.100];
let res = arr.shift();
console.log(arr); // [2, 100]
console.log(res); / / 1
Copy the code

unshift()

Definition: Add one or more elements to the beginning of an array and (this method modifies the original array)

Note: This method returns the new length of the array

let arr = [1.2.100];
let res = arr.unshift(4.5.6);
console.log(arr); // [4, 5, 6, 1, 2, 100]
console.log(res); / / 6
Copy the code

reverse()

Definition: Inverts the positions of the elements in an array and returns the array.

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

splice()

There’s a reason I put this last one in, it’s a little bit more complicated than the others, and it took me a long time to understand it at first, and I was always confused with the split() ones.

Definition:

To modify an array by removing or replacing existing elements or adding new elements in place, and return the modified contents as an array.

array.splice(start,deleteCount,item1,..... ,itemX)zCopy the code

Start: Specifies the start position of the modification (counting from 0)

If it is negative, it indicates the number of digits starting from the end of the array (counting from -1, which means -n is the NTH reciprocal element and is equivalent to array.length-n) 3. If the absolute value of a negative number is greater than the length of the array, it starts at the 0th bitCopy the code

DeleteCount (Optional) : Integer, indicating the number of array elements to be removed

If deleteCount is greater than the total number of elements after start, then all elements after start will be 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 elements after start), then all elements of the array after start are deleted. 3. If deleteCount is 0 or negative, the element is not removed. In this case, at least one new element should be added.Copy the code

item1, item2, … (optional)

To add elements to an array, start at the start position. If not specified, splice() will remove only the array elements.

Insert “Chocolate” starting at position 2

let arr = ['one'.'two'.'three'];

arr.splice(2.0.'Chocolate');
console.log(arr);// [ 'one', 'two', 'Chocolate', 'three' ]
Copy the code

Remove 1 element from the second position and insert “Chocolate”

let arr = ['one'.'two'.'three'];

arr.splice(2.1.'Chocolate');
console.log(arr);// [ 'one', 'two', 'Chocolate' ]
Copy the code

There are also fill() and copyWithin() methods for changing an array


Mapping arrays

Array. The map () method

As described above

Array. The from () method

Definition: Create a new array by using the result of a callback call on each array item.

Let’s start with the syntax:

 Array.from(Array,callback(currentValue, index, arr))
Copy the code

A simple example:

let arr = [1.2.3];

let newArr = Array.from(arr, function (cur) {
  return cur + 10;
})
console.log(newArr);// [11, 12, 13]
Copy the code

Array concatenation

The Array concat () method

array.concat(array1[, array2, …] Concatenate one or more arrays to the original array. Join the two arrays as follows:

let arrA = [1.2.3];
let arrB = [4.5.6];
let ans = arrA.concat(arrB);
console.log(ans);// [1, 2, 3, 4, 5, 6]
Copy the code

Expansion operator

let arrA = [1.2.3];
let arrB = [4.5.6];
let ans = [...arrA, ...arrB];
console.log(ans);// [1, 2, 3, 4, 5, 6]
Copy the code

Gets a fragment of an array

Array. The slice () method

Definition: Return a new array object that is a shallow copy of the original array determined by begin and end (including begin, but not end) — the original array will not be changed.

First, grammar:

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

Begin (Optional)

  1. Extract the index at the beginning (starting at 0) from which the original array elements are extracted.
  2. If this parameter is negative, it means to start extracting from the reciprocal of the original array
  3. Slice (-2) means to extract the penultimate element from the original array to the last element (including the last element)
  4. If BEGIN is omitted, slice starts at index 0.
  5. If BEGIN is greater than the length of the original array, an empty array is returned.

End (Optional)

  1. Slice (1,4) extracts all elements of the original array from the second element to the fourth element (elements indexed 1, 2, and 3)
  2. If this parameter is negative, it indicates the number of reciprocal elements in the original array to end extraction.
  3. If end is omitted, slice is extracted to the end of the original array.
  4. If end is larger than the length of the array, slice is also extracted to the end of the array.
let fruits = ['Banana'.'Orange'.'Lemon'.'Apple'.'Mango'];
let res = fruits.slice(1.3);
let res1 = fruits.slice(1);
let res2 = fruits.slice(-1);
let res3 = fruits.slice(0, -1);
console.log(res); // [ 'Orange', 'Lemon' ]
console.log(res1);// [ 'Orange', 'Lemon', 'Apple', 'Mango' ]
console.log(res2);// [ 'Mango' ]
console.log(res3);// [ 'Banana', 'Orange', 'Lemon', 'Apple' ]
Copy the code

Convert an array

join()

Definition:

Concatenate all the elements of an array (or an array-like object) into a string and return the string. If the array has only one item, the item is returned without a delimiter.

Grammar:

arr.join(separator)
Copy the code

A simple example:

let arr = ['one'.'two'.'three'];
let res = arr.join(A '^');
let res1 = arr.join('&');

console.log(res); // one^two^three
console.log(res1); // one&two&three
Copy the code

split()

Definition:

Splits a String into an array of substrings using the specified separator String, with a specified separator String to determine the location of each split.

Grammar:

str.split([separator[, limit]])
Copy the code
const str = 'The best Chocolate';

const words = str.split(' ');
console.log(words); // [ 'The', 'best', 'Chocolate' ]
console.log(words[2]); // Chocolate
Copy the code

toString()

Definition:

Returns a string representing the specified array and its elements.

When an array is treated as a text value or concatenated, its toString method is automatically called.

Grammar:

arr.toString()
Copy the code
let arr = ['one'.'two'.'three'];
console.log(arr.toString()); // one,two,three
Copy the code

Flattening of arrays

flat()

Definition:

Recursively traversing the array at a specified depth, combining all elements with the elements of the subarray traversed into a new array returned.

Grammar:

var newArray = arr.flat([depth])
Copy the code

parameter

Depth optionally specifies the structure depth to extract the nested array. The default value is 1. Return value A new array containing all the elements of the array and its subarrays.

const arr1 = [0.1.2[3.4]].console.log(arr1.flat()); // [0, 1, 2, 3, 4]

const arr2 = [0.1.2[[[3.4]]]];
console.log(arr2.flat(2)); // [0, 1, 2, [3, 4]]
Copy the code

The memo

Girlfriend said: touched!

In this paper, the reference

Thank you very much

  • “Array methods” from detailed manipulation of JS arrays to a brief analysis of V8 array.js
  • MDN_Array
  • Review the 15 common array operations in JS through examples (cheat list)
  • JS array kit Kat hookup
  • Several non-low operations on the JS array

The last

Article output is not easy, but also hope you support a wave of small partners!

Past picks:

Little lion front note warehouse

Leetcode -javascript: LeetCode force link javascript solution warehouse, front end of the line (mind map)

If this project helped you, please submit your code in the Issues, 🤝 welcome to contribute, Give a ⭐️ if this project helped you!

Visit Chaoyi blog for reading and playing

Learning is like rowing upstream: not to advance is to drop backCopy the code