"Array Method" A series of JS array operations written to girlfriends (recommended collection | with mind map included)

"Array Method" A series of JS array operations written to girlfriends (recommended collection | with mind map included)

Preface

Recently, with my girlfriend, cough cough... (you may be hit if you say it) I learned the JS array method. In a few words, I can t tell the result of the specific method when I actually use it or when I encounter it.

Today I'm going through a good sort out this article about the method JS array, so that we pass this article array series of operations, at the same time, during the interview or work can also write code. Secondly, I wrote this to my girlfriend. Will she be moved to cry when she sees it? Will it? Will it?

Do you have a girlfriend?

Ah, this...Is this important?

(You may not be able to see it clearly on the mobile phone) To obtain a high-definition PDF, please reply to the WeChat public account [Vue] [Array method]

Reading notes

Straightforward, let me first introduce the overall directory structure of this article, and introduce the general content I will output.

Obviously, there are many and many methods of arrays, but some of them are rarely used in actual work or interviews. Therefore, I will not propose all the methods and analyze them. Then, I will try to use more detailed and concise language to introduce the more important methods, and give a few examples at the same time, and the self-test cases will deepen and consolidate you.

Secondly, this article will also mention interview questions, such as classic flattening questions, array deduplication , merging , sorting, methods of changing the original array, methods of not changing the original array , and so on.

Okay, let's get into the text~

Array traversal

I still remember this year s Kuaishou interviewer asked a classic interview question: Tell me about the array traversal method you know?

I think you will encounter this question during interviews. One of the questions the interviewer asks is to examine your mastery of array methods, and the other is to choose one of the methods you mentioned to continue in-depth inquiry, such as reduce, mapuse and so, therefore, I will array traversal as the first module to explain.

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
 

for..of loop

Extracted from the MDNprevious sentence, the for...ofstatement traverses the iterable object to define the data to be iterated. Simply put, it is for...oftraversed value.

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

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

for...in loop

Taken from the MDNprevious sentence, the for...instatement iterates the enumerable properties of the object in any order . Simply put, it is for...intraversed key. For an array, it keycorresponds to the subscript index of the array .

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

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

array.forEach() method

Let's introduce the syntax first:

array.forEach(callback(currentValue, index, arr), thisArg)
 

callback: a function executed for each element in the array, the function receives one to three parameters

currentValue the current element being processed in the array index (optional) the index of the current element being processed in the array arr (optional) the array being operated by the forEach() method thisArg optional parameter, when the callback function is executed, it is used as this value

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' ]
 

From the above example, learned forEachneed to pass a callback function, and that the three parameters, the latter two are optional, then how to make the code a little more elegant and beautiful it, while the latter two parameters can be added as needed:

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

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

Difficult point , I think small partners, should be the last one thisArgin doubt of it, now to explain:

function Foo() {
  this.sum = 0;
  this.cnt = 0;
}
//  doSth  
Foo.prototype.doSth = function (arr) {
  arr.forEach(function (cur) {
    this.sum += cur;
    this.cnt++;
  }, this) //this  
}

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)
 

Note: If used to pass in function parameters, the thisArg parameter will be ignored, because the arrow function binds this value lexically.

Therefore, if for normal function, it can be seen as thisresolved by the form of parameter passing can not inherit the problem, of course, a function of the way by the arrow is a good choice!

map traversal

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

Let's introduce the syntax first:

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

callback: a function executed for each element in the array, the function receives one to three parameters

currentValue the current element being processed in the array index (optional) the index of the current element being processed in the array arr (optional) the array being operated by the map() method thisArg optional parameter, when the callback function is executed, it is used as this value

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' ]
 

Difficult point , I think small partners, with the pre-issue, and this understanding thisArgshould not have much problem, right, look at the following example:

function Foo() {
  this.sum = 0;
  this.cnt = 0;
}
//  doSth  
Foo.prototype.doSth = function (arr) {
  let newArr = arr.map(function (cur) {
    this.sum += cur;
    this.cnt++;
    return cur + 10;
  }, this) //this  
  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
 

Some small operations ~

let arr = [1, 4, 9, 16];
let res = arr.map(Math.sqrt); // Math sqrt 
console.log(res); //[ 1, 2, 3, 4 ]
 

Summary :

  • mapWithout modifying the original array itself calls it (of course, can callbackchange the implementation of the original array)

When the callback function does not return a value, each value of the new array isundefined

  • thisThe final value relative to the callbackobservability function is based on this rule, that is, thispointing to the problem
  • map Will return a new array

reduce traversal

Definition: each element in the array provided by your perform a reducerfunction (in ascending order execution), summarizes the results of single return value.

Let's introduce the syntax first:

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

callback: a function executed for each element in the array, the function receives one to 4 parameters

accumulator currentValue current value currentIndex current index array array initialValue as the value of the first parameter when the callback function is called for the first time. If no initial value is provided, the first element in the array will be used. Calling reduce on an empty array with no initial value will report an error.

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
 

After reading the above code, you may still Mongolia, about how much output, in conjunction with the following gifaction figure come to understand it:

Difficulty , I think my friends should be confused about so many parameters. Let's show them with some small operations, and provide some self-test questions to deepen and consolidate~

let arr = [1, 2, 3, 4, 5];
let res = arr.reduce((acc, cur) => {
  return acc + cur;
}, 0)
console.log(res);//15
 

Self-test questions: see what is output below?

[1, 2, 3, 4].reduce((x, y) => console.log(x, y));
 
  • A: 1 2and 3 3and6 4
  • B: 1 2and 2 3and3 4
  • C: 1 undefinedand 2 undefinedand 3 undefinedand4 undefined
  • D: 1 2and undefined 3andundefined 4
answer

Answer: D

reducer The function receives 4 parameters:

  1. Accumulator (acc)
  2. Current Value (cur)
  3. Current Index (idx)
  4. Source Array (src)

reducer The return value of the function will be assigned to the accumulator, the return value is remembered in each iteration of the array, and finally becomes the final single result value.

reducerThe function also has an optional parameter initialValue, which will be the value of the first parameter when the callback function is called for the first time. If not provided initialValue, the first element in the array will be used.

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

In the first call, the accumulator xis 1, the current value y is 2, print out the accumulator and the current values: 1and 2.

In the example, our callback function does not return any value, it just prints the accumulator value and current value. If the function does not return a value, it returns by default undefined. In the next call, the accumulator is undefined, and the current value is "3", so the undefinedsum 3is printed out.

In the fourth call, the callback function still has no return value. The accumulator is again undefined, and the current value is "4". undefinedAnd 4is printed out.


Summary :

  • If the array is empty and not provided initialValue, it will be thrown TypeError.
  • If no initialValue, reducewill begin where it left index 1 callbackmethod, skip the first index. If provided initialValue, start at index 0.
  • accIs the return value of the passed function, if it is console.log, it returns the default valueundefined

filter()

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

Let's introduce the syntax first:

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

callback: a function executed for each element in the array, the function receives one to three parameters

currentValue The current element being processed in the array index (optional) The index of the current element being processed in the array arr (optional) The array thisArg being operated by the filter() method (optional parameter), when the callback function is executed, it is used as this value

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
//2 1
//3 2
//4 3
//5 4
console.log(newArr); //[ 2, 4 ]
 

About thisArgRelated referred to above may be array.forEach() part.

Simply put, it is to return the results that meet the conditions.

every()

Definition: All elements within an array test whether can pass a test a specified function, it returns a Booleanvalue type.

Let's introduce the syntax first:

array.every(function(currentValue, index, arr), thisArg)
 

callback: a function executed for each element in the array, the function receives one to three parameters

currentValue the current element being processed in the array index (optional) the index of the current element being processed in the array arr (optional) the array being operated by the every() method thisArg optional parameter, when the callback function is executed, it is used as this value

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

 

About thisArgRelated referred to above may be array.forEach() part.

Simply put, it is to return whether the result can meet the specific conditions , and return it with a Boolean value.

some()

Definition: the test array is not at least one element by the test function is provided, it returns a Booleanvalue of type

Let's introduce the syntax first:

array.some(function(currentValue, index, arr), thisArg)
 

callback: a function executed for each element in the array, the function receives one to three parameters

currentValue the current element being processed in the array index (optional) the index of the current element being processed in the array arr (optional) the array thisArg being operated by the some() method (optional parameter), when the callback function is executed, it is used as this value

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
 

About thisArgRelated referred to above may be array.forEach() part.

Simply put, it is to return whether there is at least 1 result that meets a specific condition , and return it with 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, it returns undefined.

findIndex: The index of the first element in the array that passed the test function. Otherwise, return -1.

Let's introduce the syntax first:

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

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

callback: a function executed for each element in the array, the function receives one to three parameters

The current element being processed in the elemnet array index (optional) the index of the current element being processed in the array arr (optional) the array thisArg being operated by the find method optional parameter, when the callback function is executed, it is used as this value

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
 

keys and values and entries

definition:

  • keys()The method returns an Array Iterator object containing each index key in the array .
  • values()Method returns a new Array Iteratorobject that contains an array for each value of the index
  • entries()Method returns a new Array Iteratorobject that contains an array of each index key/value pairs .
arr.keys()
arr.values()
arr.entries()
 

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' ]
 

Well, this is basically an array of ways to traverse on introductions, perhaps there are other methods, but the original aim, then we will explore changing the original array methods.

Change the original array method

Before I read about the Vuedata source analysis hijacking thing I read in a blog post junior partner should be aware that there is there mentioned with the decorator pattern to solve an array of problems can not be processed. Among them, there is a mention of methods for changing the original array, which need to continue to be observed recursively. So, next, let's discuss their use separately:

sort()

As for why I was ranked first, yes, I encountered it in the interview. At that time, I said to a certain interviewer that the default sorting is from small to large by default. After studying, I found that it is not...

Let's introduce the syntax first:

arr.sort([compareFunction])
 

compareFunction is optional and is used to specify functions to be arranged in a certain order. If omitted, the elements are sorted according to the Unicode position of each character in the converted string.

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

Simple example:

let arr = [1, 10, 2, 5, 8, 3];

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

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

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

push()

Some operations similar to stacks and queues

Note that push()the length of the array will be returned after success.

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

pop()

Some operations similar to stacks and queues

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

shift()

Some operations similar to stacks and queues

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

unshift()

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

Note : This method will return 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
 

reverse()

Definition: Reverse the position of the elements in the array and return the array.

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

splice()

I put this last for a reason, it is more complicated than several other point, I just started it took a long time to understand the old, and had been working with split()them could not tell.

definition:

Modify the array by deleting or replacing existing elements or adding new elements in place, and return the modified content in the form of an array.

array.splice(start,deleteCount,item1,.....,itemX)z
 

start: Specify the starting position of the modification (counting from 0)

	1.  
	2.  -1 -n n array.length-n 
	3.  0 
 

deleteCount(optional): integer, indicating the number of array elements to be removed

	1.   deleteCount   start   start  			 (  start  )
	2.   deleteCount  array.length - start( 		    start ) start 
	3.   deleteCount   0  		    
 

item1, item2, ... (optional)

The elements to be added to the array start at the start position. If not specified, splice() will only delete array elements.

Insert "Chocolate" from the 2nd position

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

arr.splice(2, 0, 'Chocolate');
console.log(arr);//[ 'one', 'two', 'Chocolate', 'three' ]
 

Delete 1 element from the 2nd position and insert "Chocolate"

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

arr.splice(2, 1, 'Chocolate');
console.log(arr);//[ 'one', 'two', 'Chocolate' ]
 

Or is it seven mainstream methods, as well as to change the original array fill()and copyWithin()method, small partners can continue to study ~


Array mapping

Array.map() method

Already introduced above

Array.from() method

Definition: By using an array on each item callbackto create a new array result of the call.

Let's introduce the syntax first:

 Array.from(Array,callback(currentValue, index, arr))
 

Simple example:

let arr = [1, 2, 3];

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

Concatenation of arrays

Array.concat() method

array.concat(array1[, array2, ...])Connect one or more arrays to the original array. As shown below, concatenate the two arrays:

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

Spread operator

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

Get a fragment of the array

Array.slice() method

Definition: Returns a new array object, the object is a made beginand endthe original array decision shallow copy (including begin, not including end) - original array is not changed.

First introduce the syntax:

arr.slice([begin[, end]])
 

begin (optional)

  1. Extract the starting index (starting from 0), and extract the original array element from this index.
  2. If the parameter is negative, it means to start extracting from the penultimate element in the original array
  3. slice(-2) means to extract the penultimate element to the last element in the original array (including the last element)
  4. If begin is omitted, the slice starts at index 0.
  5. If begin is greater than the length of the original array, an empty array will be returned.

end (optional)

  1. slice(1,4) will extract all elements from the second element to the fourth element in the original array (elements with index 1, 2, 3)
  2. If the parameter is a negative number, it means that the last element in the original array is extracted.
  3. If end is omitted, the slice will be extracted to the end of the original array.
  4. If end is greater than the length of the array, the slice will also be extracted to the end of the original 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' ]
 

Convert the array

join()

definition:

Concatenate all the elements of an array (or an array-like object) into a string and return this string. If the array has only one item, then that item will be returned without using the separator.

syntax:

arr.join(separator)
 

Simple example:

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

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

split()

definition:

Using the specified delimiter string to a Stringtarget string is divided into sub-arrays, at a specified string to determine the location of each division split.

syntax:

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

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

toString()

definition:

Returns a string representing the specified array and its elements.

When an array is used as a text value or string concatenation will its toStringmethod.

syntax:

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

Flattening of arrays

flat()

definition:

Recursively traverse the array according to a specified depth, and merge all the elements with the elements in the traversed sub-array into one return.

syntax:

var newArray = arr.flat([depth])
 

parameter

depth can optionally specify the depth of the structure of the nested array to be extracted, the default value is 1. The return value is a new array containing all the elements in the array and sub-arrays.

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 ] ]
 

memorandum

The girlfriend said: I am moved!

This article references

Thank you guys~

At last

The output of the article is not easy, and I hope you all support a wave!

Past selections:

Note Warehouse of Little Lion Front End

Leetcode-javascript: LeetCode's JavaScript problem solving warehouse, front-end problem-brushing route (mind map)

Friends can submit their own problem-solving code in Issues, Welcome to Contributing, you can punch in and swipe the problem, Give a if this project helped you!

Visit Chaoyi's blog , which is convenient for friends to read and play~