preface

Recently, a student was asked about this in an interview, and did not give a good answer, so I decided to write a temporary issue about the array method in JavaScript. (Unexpectedly, it is approaching the Chinese New Year, and there is a big demand, so I will not say that because I am busy with work, writing code is easier than writing text.)

1. Methods related to data structures

If you are familiar with data structures, you should know the stack and queue data structures. Some of JavaScript’s array methods fit the stack and queue approach to data structures implemented with arrays.

1.1 Array. Prototype. Push

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

  • Whether to change the original array: Yes
  • Parameters:
    • ElementN: The element added to the end of the array
  • Return value: the value of the length property after the element is added to the array

This method is similar to the push method on the stack, which pushes an element onto the stack:

const stack = [];
stack.push(1);	/ / 1
console.log(stack); / / [1]

const stack1 = [];
stack1.push(1.2); / / 2
console.log(stack1); / / [1, 2]
Copy the code

1.2 Array. Prototype. 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.

  • Whether to change the original array: Yes
  • Parameters: no
  • Return value: The element removed from the array (undefined if the array is empty)

This method is similar to the pop-up method on the stack, which pops the element at the top of the stack:

const stack = [1, 2, 3, 4, 5]; stack.pop(); // 5 console.log(stack); // [1, 2, 3, 4] const stack1 = []; stack1.pop(); // undefined console.log(stack1); / / []Copy the code

1.3 Array. The prototype. The 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).

  • Whether to change the original array: Yes
  • Parameters:
    • ElementN: The element or elements to be added to the beginning of an array
  • Return value: the value of the length property after the element is added to the array

This method is a bit like the enqueue operation, which enlists one or more elements:

const queue = [3, 4, 5];
queue.unshift(2); // 4
console.log(queue); // [2, 3, 4, 5]

const queue1 = [3, 4, 5];
queue1.unshift(1, 2); // 5
console.log(queue1); // [1, 2, 3, 4, 5]
Copy the code

1.4 Array. The prototype. The shift

The shift() method removes the first element from the array and returns the value of that element. This method changes the length of the array.

  • Whether to change the original array: Yes
  • Parameters: no
  • Return value: The element removed from the array (undefined if the array is empty)

This method is somewhat similar to the dequeue operation and somewhat similar to the stack eject operation:

const queue = [3, 4, 5]; queue.shift(); // 3 console.log(queue); // [4, 5] const queue1 = []; queue1.shift(); // undefined console.log(queue1); / / []Copy the code

1.5 summary

In fact, similar to or somewhat similar to, JavaScript itself does not provide a rigorous implementation of queue or stack data structure method, but through the flexible use of these four apis, in fact, can be relatively flexible implementation of queue or stack function. But if you really want to emulate stacks or queues in a production environment with these four apis, encapsulate them a little. If you’re interested, try it out after you learn about stacks and queues.

1.6 Try it yourself?

Let’s implement what the above API does.

Write a push 1.6.1 imitation

Let’s start with a push:

Array.prototype.myPush = function(... args) { let top = this.length; for (let i = 0; i < args.length; i++) { this[top] = args[i]; top++; } return this.length; }; const stack = []; stack.myPush(1); // 1 console.log(stack); // [1] const stack1 = []; stack1.myPush(1, 2); // 2 console.log(stack1); / / [1, 2]Copy the code

Note: Do not use the arrow function, otherwise there will be some problems with this pointing, about this pointing problem, because it is not the focus of this issue, so I will not talk about it for now.

1.6.2 copy write pop

How about Pop?

Array.prototype.myPop = function() { const topEle = this[this.length - 1]; this.length > 0 && this.length--; return topEle; }; const stack = [1, 2, 3, 4, 5]; stack.myPop(); // 5 console.log(stack); // [1, 2, 3, 4] const stack1 = []; stack1.myPop(); // undefined console.log(stack1); / / []Copy the code

1.7 summary

Digression, write a method, whether copy write or, or their own hair open. The first thing to determine is the input parameter and return value of the function. At the same time, I personally tend to write all pure functions. As for unshift and shift imitation, I won’t write it here, it’s a little bit more complicated, but it’s not too complicated.

2. Sequence-related methods

2.1 Array. Prototype. Sort

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

  • Whether to change the original array: Yes
  • Parameters:
    • CompareFunction: Used to specify functions in a certain order. If omitted, the element is sorted by the Unicode loci of each character in the converted string.
  • Return value: sorted array (original array)

compareFunction

  • Parameters:
    • A: The first element for comparison
    • B: The second element for comparison
  • Return value: number
  • Description:
    • If compareFunction(a, b) is less than 0, then A is placed 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 placed before A

In short, the sort method accepts a callback function. This callback takes two elements a and B from the array to be compared and returns a number. Sort performs the operations described above on the array based on the value of number.

Watch a 🌰 :

const numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
}); // [1, 2, 3, 4, 5]
Copy the code

Sort this thing, if you expand it it’s too much, so I’m not going to expand it. If you are interested in sorting and JavaScript sorting, I recommend reading these two articles:

  • Let’s talk about sorting algorithms
  • Sorting in a V8 engine

2.2 Array. The prototype. The 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.

  • Whether to change the original array: Yes
  • Parameters: no
  • Return value: reversed array (original array)

Nothing to say, is to reverse the array, so look at 🌰 :

const arr = [1, 2, 3, 4, 5];
arr.reverse(); // [5, 4, 3, 2, 1]
Copy the code

3. Methods related to traversal

3.1 Array. Prototype. Every

The every() method tests whether all elements in an array pass the test of a given function. It returns a Boolean value.

  • Whether to change the original array: No
  • Parameters:
    • Callback: callback function
    • ThisArg: this value used when executing callback
  • Return value: Boolean (Whether all elements pass the callback test)

callback

  • Parameters:
    • Element: The current element of the array when callback is executed
    • Index: indicates the index of the current element
    • Array: the current array of the calling method
  • Return value: Boolean
  • Description: Determines whether the current element meets the criteria for callback

An 🌰 :

const test = [1, 2, 3, 4, 5];

const isMoreThanThree = (num) => {
  return num > 3;
};

test.every(isMoreThanThree); // false
Copy the code

3.2 Array. Prototype. Some

The some() method tests that at least one element in the array passes the provided function test. It returns a Boolean value.

  • Whether to change the original array: No
  • Parameters:
    • Callback: callback function
    • ThisArg: this value used when executing callback
  • Return value: Boolean (If at least 1 element passes the callback test)

callback

  • Parameters:
    • Element: The current element of the array when callback is executed
    • Index: indicates the index of the current element
    • Array: the current array of the calling method
  • Return value: Boolean
  • Description: Determines whether the current element meets the criteria for callback

An 🌰 :

const test = [1, 2, 3, 4, 5];

const isMoreThanThree = (num) => {
  return num > 3;
};

test.some(isMoreThanThree); // true
Copy the code

3.3 Array. The prototype. The find

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

  • Whether to change the original array: No
  • Parameters:
    • Callback: callback function
    • ThisArg: this value used when executing callback
  • Return value: the value of the first element in the array that satisfies the provided test function, otherwise undefined is returned.

callback

  • Parameters:
    • Element: The current element of the array when callback is executed
    • Index: indicates the index of the current element
    • Array: the current array of the calling method
  • Return value: Boolean
  • Description: Determines whether the current element meets the criteria for callback

An 🌰 :

const test = [1, 2, 3, 4, 5];

const isThree = (num) => {
  return num === 3;
};

const isSeven = (num) => {
  return num === 7;
};

test.find(isThree); // 3
test.find(isSeven); // undefined
Copy the code

3.4 Array. Prototype. 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.

Very similar to the one above.

3.5 Array. Prototype. ForEach

The forEach() method performs the given function once on each element of the array.

  • Whether to change the original array: No
  • Parameters:
    • Callback: callback function
    • ThisArg: this value used when executing callback
  • Return value: undefined

callback

  • Parameters:
    • Element: The current element of the array when callback is executed
    • Index: indicates the index of the current element
    • Array: the current array of the calling method
  • Return value: No

Think about how you got this wrong all the time when you first started with the front end. It’s just that the instruction for loop is getting used to it, and the coding is bad. Two nos — no changes to the array, no return value (undefined). Ok, for example 🌰 :

const test = [1, 2, 3, 4, 5]; const log = (val) => { console.log(val); }; test.forEach(log); // Print 1, 2, 3, 4, 5Copy the code

3.6 Array. The prototype. The 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.

  • Whether to change the original array: No
  • Parameters:
    • Callback: callback function
    • ThisArg: this value used when executing callback
  • Return value: Array(a new Array consisting of the result of each element of the original Array executing the callback function.)

callback

  • Parameters:
    • Element: The current element of the array when callback is executed
    • Index: indicates the index of the current element
    • Array: the current array of the calling method
  • Return value: The element that forms the new array

I used to confuse this method with forEach, but now I still haven’t learned English well. A map b map C map D map So, map will generate an array that maps to the original array. So for example 🌰 :

const test = [1, 2, 3, 4, 5];

const double = (num) => {
  return num * 2;
};

const doubleList = test.map(double);

console.log(doubleList); // [2, 4, 6, 8, 10]
Copy the code

3.7 Array. The prototype filter

The filter() method creates a new array containing all the elements of the test implemented through the provided function.

  • Whether to change the original array: No
  • Parameters:
    • Callback: callback function
    • ThisArg: this value used when executing callback
  • Return value: Array(a new Array of elements that pass the test, or an empty Array if none of the Array elements pass the test.)

callback

  • Parameters:
    • Element: The current element of the array when callback is executed
    • Index: indicates the index of the current element
    • Array: the current array of the calling method
  • Return value: Boolean
  • Description: Determines whether an element passes a test

The naming of this method is also easy to understand, for example 🌰 :

const test = [1, 2, 3, 4, 5]; const isMoreThanThree = (num) => { return num > 3; }; const moreThanThreeList = test.filter(isMoreThanThree); console.log(moreThanThreeList); / / [4, 5]Copy the code

3.8 Array. Prototype. 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.

  • Whether to change the original array: No
  • Parameters:
    • Callback: callback function
    • InitialValue: 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.
  • Return value: cumulative processing result of the function

callback

  • Parameters:
    • Accumulator: The return value of the accumulator callback; It is the cumulative value, or initialValue, returned when the callback was last called
    • Element: The current element of the array when callback is executed
    • Index: indicates the index of the current element
    • Array: the current array of the calling method
  • Return value: Boolean
  • Description: Determines whether an element passes a test

This method, which is very, very powerful, can be used in almost any scenario where you iterate through an array and get a return value.

Such as:

  • Mathematical calculation: cumulative, factorial, find the maximum minimum……
  • Array operations: de-weight, flattening……
  • Function: PIPE (executes function combinations from left to right)
  • , etc.

Here’s an example of a pipe implementation 🌰 :

const pipe = (... fns) => { return (arg) => { return fns.reduce((res, fn) => { return fn(res); }, arg); }; };Copy the code

3.9 summary

It is not difficult to find that the API is too similar to array iteration methods, but in fact these API semantics are very good, use more, naturally familiar. Then why not implement one yourself?

3.10 copy write the reduce

Array.prototype.myReduce = function (fn, initialValue) { let ret = initialValue || this[0]; let idx = initialValue ? 0:1; while (idx < this.length) { ret = fn(ret, this[idx], idx, this); idx++; } return ret; }; const test = [1, 2, 3, 4, 5]; const add = (num1, num2) => { return num1 + num2; }; test.myReduce(add); // 15 test.myReduce(add, 10); / / 25Copy the code

The writing is relatively rough, and other methods and ideas are similar. If you are interested, you can write and have a look. After writing, you can deepen your understanding.

4 Other Methods

4.1 Array. Prototype. Flat

The Flat () method recurses through the array of numbers at a specified depth and returns all the elements in a new array combined with the elements in the traversed subarray.

  • Whether to change the original array: No
  • Parameter: depth(Specifies the depth of the structure to extract the nested array. The default is 1.)
  • Return value: flattened array (a new array containing all the elements of the array and its subarrays.)

I had always thought that flattening was of little use in actual production. It was not until later, when the business I maintained became complicated, that I needed to use map to classify and manage data and then finally took it out and merged it, that I found this method was quite sweet. An 🌰 :

const test = [1, [2, 3], [4, [5, 6]]];

test.flat(1); // [1, 2, 3, 4, [5, 6]]

test.flat(2); // [1, 2, 3, 4, 5, 6]
Copy the code

Do it yourself? In fact, I really like the idea of using a stack to achieve flattening, MDN has this version, but I have seen related articles about this method is rarely mentioned.

const test = [1, [2, 3], [4, [5, 6]]]; const flatten = (list) => { const stack = [...list]; const ret = []; while (stack.length) { const topElem = stack.pop(); if (Array.isArray(topElem)) { stack.push(... topElem); } else { ret.push(topElem); } } return ret.reverse(); }; flatten(test); // [1, 2, 3, 4, 5, 6]Copy the code

The idea is fairly straightforward: flattening an array is obviously a deep search process, and deep search requires stacks, so the stack template can be used. One thing that maybe needs to be rotated a little bit is the last thing that inverts the array. Of course, if it were written with complete common sense, then every step on the stack would be an inverted element.

5. Conclusion

In fact, there are a lot of methods are also very common, but because of the length reasons, here will not expand temporarily, such as:

  • Array.prototype.splice
  • Array.prototype.join
  • Array.prototype.concat

Arrays are all too common data structures in development, and the methods of arrays must be memorized.

In fact, I personally do not like to write that kind of document article, but it is inevitable to write that type of article. This article should have been sent out two weeks ago on the weekend, but it was delayed because I was really busy with my work recently. Insist, really is not an easy thing, write an article so, learning is so.

In the past two days, Miss Banbi has released a new song, let’s sing “Bright” by Miss Banbi here. Some things, is to stick to see the hope, but in my opinion, front-end learning is really not that difficult, maybe just the method is not right. I hope everyone can stick to it and find their own light in the distance.

Finally, thank you for reading and welcome to point out the questions and comments in the article.