Summary of several common methods of JavaScript arrays

Summary of several common methods of JavaScript arrays

1. Introduction

There are too many array methods. This article records some array methods that I tend to remember incorrectly for consolidation and review.
Other array methods will be added gradually in the future.
Making good use of array methods can make data processing elegant and simple.

So let’s get started:

2. filter()

describe:

filter() method creates a new array and adds all the elements that meet the condition to the created new array.

grammar:

Array.filter(callback(element, index, array) { // function body}, thisValue)


parameter:

callback and thisValue :

parameter Is it optional? describe
Parameter 1 callback Required A function to test each element of an array. Return true if the element passes the test and is retained, false if not. It receives three parameters.
Parameter 2 thisValue Optional The value to use for this when the callback is executed.
The object is used as the callback for this execution and is passed to the function.
If thisValue is omitted, the value of "this" is "undefined"

The callback parameter list:

parameter Is it optional? describe
Parameter 1 element Required Current element
Parameter 2 index Optional The index value of the current element
Parameter three array Optional The array on which filter is called

Parameters of thisValue:

The value to use for this when callback is executed.

Return value:

Is a new array consisting of the return value of filter() function parameter

Example:

let users = [
  {id: 11, name: "Sun Wukong"},
  {id: 21, name: "Zhu Bajie"},
  {id: 31, name: "Sha Monk"}
];

// Returns an array of the first two users let filterUsers = users.filter(item => item.id < 31);

console.log(filterUsers.length); // 2

3. map()

describe:

map() method creates a new array where each element is the return value of calling the given function once.

grammar:

Array.map(callback(currentValue, index, array) { // function body}, thisValue)


parameter:

callback and thisValue

parameter Is it optional? describe
Parameter 1 callback Required A callback function to be run for each element in the array. It receives three parameters.
Parameter 2 thisValue Optional The value to use for this when the callback is executed.
The object is used as the callback for this execution and is passed to the function.
If thisValue is omitted, the value of "this" is "undefined"

The callback parameter list:

parameter Is it optional? describe
Parameter 1 element Required Current element
Parameter 2 index Optional The index value of the current element
Parameter three array Optional The array on which filter is called

Parameters of thisValue:

The value to use for this when callback is executed.

Return value:

It is a new array consisting of the results of executing the callback function on each element of the original array.

Example:

let number = [1, 2, 3].map(item => item + 1);

console.log(lengths); // 2, 3, 4

4. sort()

describe:

map() method modifies the original array to change the order of elements

Note: The default sort order is when converting elements to strings and then comparing their UTF-16 code unit value sequences.

grammar:

Array.sort( compareFunction )


parameter:

compareFunction

parameter Is it optional? describe
Parameter 1 compareFunction Optional Function that specifies the sort order. If omitted, the elements are sorted according to the Unicode positions of the characters in the converted string.

Parameter list of compareFunction:

parameter Is it optional? describe
Parameter 1 firstEl Required The first element to compare.
Parameter 2 secondEl Required The second element to compare.

compareFunction Return Value

Returns a number indicating the order of the two values

  • If a is less than b, a should appear before b in the sorted array, and a value less than 0 is returned.
  • If a is equal to b, return 0.
  • If a is greater than b, returns a value greater than 0.

Return value:

The return value is a sorted array, but the return value is usually ignored because the original array is modified.

Example:

let number = [1, 2, 3].map(item => item + 1);

console.log(lengths); // 2, 3, 4

5. reduce()

describe:
The reduce() method executes the callback function for each element in the array in sequence (in ascending order), excluding elements in the array that have been deleted or have never been assigned a value. Evaluates its result into a value.

Note: reduce() can be used as a higher-order function for function compose.

grammar:

Array.reduce(callback(accumulator, currentValue, index, array), initialValue)


parameter:

callback and initialValue

parameter Is it optional? describe
Parameter 1 callback Required Executes the function for each array element in the array (if there is no initialValue, the first value will not execute the change function). It receives four parameters.
Parameter 2 initialValue Optional The initial value of the callback function

The callback parameter list:

parameter Is it optional? describe
Parameter 1 accumulator Required The accumulator accumulates the return value of the callback; it is the accumulated value returned by the last call to the callback, or the initialValue.
Parameter 2 currentValue Required Current element
Parameter three index Optional The index value of the current element
Parameter 4 array Optional The array on which reduce() is called

Parameters of initialValue:

The value to be used as the first argument when callback function is first called. If no initial value is provided, the first element in the array will be used as the initial value. Calling reduce on an empty array with no initial value will result in an error.

Return value:

The result of the function accumulation processing is executed after all callback functions are accumulator .

Note: The return value of our reducer function is assigned to the accumulator, which is remembered on each iteration of the array and becomes the final single result value.

Example:

let number = [1, 2, 3, 4];

let result = number.reduce((sum, current) => sum + current, 0);

console.log(result); // 10

6. forEach()

describe:

The reduce() method executes the callback function for each element in the array in sequence (in ascending order), excluding elements in the array that have been deleted or have never been assigned a value. Evaluates its result into a value.

Note: reduce() can be used as a higher-order function for function compose.

grammar:

Array.forEach(callback(currentValue , index , array), thisValue)

parameter:

callback and thisValue

parameter Is it optional? describe
Parameter 1 callback Required Executes a function for each element in an array, taking three arguments.
Parameter 2 thisValue Optional The value to use for this when the callback is executed.
The object is used as the callback for this execution and is passed to the function.
If thisValue is omitted, the value of "this" is "undefined"

The callback parameter list:

parameter Is it optional? describe
Parameter 1 currentValue Required Current element
Parameter 2 index Optional The index value of the current element
Parameter three array Optional The array itself on which forEach() is called

Parameters of thisValue:

The value to use for this when callback is executed.

Return value:

This method has no return value.

Example:

let number = [1, 2, 3, 4];

number.forEach((item, index ,array) => {
 console.log(item); // 1/2/3/4
});

7. Method List

Method attributes:

method Change the original array Return value description describe
filter() no The new filtered array Filters
map() no The new array after the loop cycle
sort() yes For the sorted array Sorting
reduce() no The result after the function accumulates and processes accumulator
forEach() yes No return value is undefined cycle

This is the end of this article summarizing several common methods of JavaScript arrays. For more relevant content on several common methods of JavaScript arrays, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

8. References

MDN Chinese official website https://developer.mozilla.org/zh-CN/
W3School Simplified Chinese version https://www.w3school.com.cn/

You may also be interested in:
  • JS one-dimensional array converted to three-dimensional array method
  • JavaScript Array reduce() Method
  • Detailed Example of JavaScript Array Methods
  • Detailed explanation of the new array methods in JavaScript es6
  • Detailed explanation of JS array methods
  • Complete list of javascript array methods

<<:  Six-step example code for JDBC connection (connecting to MySQL)

>>:  Several navigation directions that will be popular in the future

Recommend

Detailed explanation of CSS margin collapsing

Previous This is a classic old question. Since a ...

First experience of creating text with javascript Three.js

Table of contents Effect Start creating text Firs...

Detailed explanation of vue simple notepad development

This article example shares the specific code of ...

Detailed explanation of how to use the Vue date time picker component

This article example shares the specific code of ...

Raspberry Pi msmtp and mutt installation and configuration tutorial

1. Install mutt sudo apt-get install mutt 2. Inst...

Vue implements image dragging and sorting

This article example shares the specific code of ...

How does MySQL connect to the corresponding client process?

question For a given MySQL connection, how can we...

Common writing examples for MySQL and Oracle batch insert SQL

Table of contents For example: General writing: S...

MySQL 5.7 deployment and remote access configuration under Linux

Preface: Recently I am going to team up with my p...

Analysis of the operating principle and implementation process of Docker Hub

Similar to the code hosting service provided by G...

MySQL Billions of Data Import, Export and Migration Notes

I have been taking a lot of MySQL notes recently,...

Example of how to check the capacity of MySQL database table

This article introduces the command statements fo...

How to choose the right MySQL datetime type to store your time

When building a database and writing a program, i...

Docker cleanup environment operation

Start cleaning carefully! List unused volumes doc...