Detailed explanation of JS array methods

Detailed explanation of JS array methods

1. The original array will be modified

1. push():

Add a new element to the array (at the end of the array)

The push() method returns the length of the new array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

2.pop():

Method to remove the last element from an array

You can receive the return value of pop(), which is the popped value "Mango"

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

3. shift():

Delete the first array element

Can receive deleted values

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();

4.unshift():

Add a new element to the array (at the beginning)

Returns the length of the new array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");

5.splice():

Used to add new items to an array

The first argument (2) defines where the new element should be added (splicing).

The second parameter (0) defines how many elements should be removed.

The remaining parameters ("Lemon", "Kiwi") define the new element to be added.

The splice() method returns an array containing the removed items.

You can also delete elements in the array by setting parameters

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
//["Banana","Orange","Lemon","Kiwi","Apple","Mango"]
 var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);
//["Orange", "Apple", "Mango"]

6. sort():

Sort an array in alphabetical order

If you are sorting numbers, you need to be careful. "25" is greater than "100" because "2" is greater than "1". We correct this problem by using a ratio function.

sort() can also sort object arrays by modifying the comparison function

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); 
 var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});//Ascending order points.sort(function(a, b){return b - a});//Descending order points.sort((a, b)=>{return b - a});//arrow function var cars = [
    {type:"Volvo", year:2016},
    {type:"Saab", year:2001},
    {type:"BMW", year:2010}
]
cars.sort(function(a, b){return a.year - b.year}); //Compare years (numbers)
cars.sort(function(a, b){//Comparison type (string)
	  var x = a.type.toLowerCase();
	  var y = b.type.toLowerCase();
	  if (x < y) {return -1;}
	  if (x > y) {return 1;}
	  return 0;
});

7. reverse():

Reverse the elements in an array

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();

2. Do not modify the original array

1. toString():

Convert an array to a string of array values ​​(comma separated).

var fruits = ["Banana", "Orange", "Apple", "Mango"]
console.log(fruits.toString())
//Banana,Orange,Apple,Mango

2.join():

All array elements can be concatenated into a single string.

It behaves similarly to toString(), but can also specify a delimiter

var fruits = ["Banana", "Orange", "Apple", "Mango"]
console.log(fruits.join(" * "))
//Banana * Orange * Apple * Mango

3.concat():

Create a new array by merging (concatenating) existing arrays. Can connect multiple

var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys); // concatenate myGirls and myBoys
 var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // concatenate arr1, arr2 and arr3

4.slice() :

The method creates a new array using a slice of an array.

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);//from the first to the last//["Orange", "Lemon", "Apple", "Mango"]
 var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3); //From the first to the third (excluding 3)
//["Orange", "Lemon"]

5.map():

Calls a provided function on each element of an array and returns the result as a new array without changing the original array.

let arr = [1, 2, 3, 4, 5]
let newArr = arr.map(x => x*2) //Shorthand arrow function //arr = [1, 2, 3, 4, 5] The original array remains unchanged //newArr = [2, 4, 6, 8, 10] Returns a new array

6. forEach():

Execute the provided function for each element in the array. No return value is given. Note the difference from the map method.

let arr = [1, 2, 3, 4, 5]
arr.forEach(x => {
    console.log(2*x)
    //return x*2 The return value is useless, this function has no return value})

7.filter():

This method judges all elements and returns the elements that meet the conditions as a new array. The conditions are written in the function! ! !

let arr = [1, 2, 3, 4, 5]
let newArr = arr.filter(value => value >= 3 )
// or let newArr = arr.filter(function(value) {return value >= 3} )
console.log(newArr)
//[3,4,5]

8.every():

This method returns a Boolean value after judging all elements. If all elements meet the judgment condition, it returns true, otherwise it returns false.

let arr = [1, 2, 3, 4, 5]
const isLessThan4 = value => value < 4
const isLessThan6 => value => value < 6
arr.every(isLessThan4 ) //false
arr.every(isLessThan6 ) //true

9.some():

This method returns a Boolean value after judging all elements. If there is an element that meets the judgment condition, it returns true. If all elements do not meet the judgment condition, it returns false.

let arr = [1, 2, 3, 4, 5]
const isLessThan4 = value => value < 4
const isLessThan6 = value => value > 6
arr.some(isLessThan4 ) //true
arr.some(isLessThan6 ) //false

10.reduce():

This method calls the return function for all elements, and the return value is the final result. The value passed in must be a function type.

let arr = [1, 2, 3, 4, 5]
const add = (a, b) => a + b
let sum = arr.reduce(add)  
 console.log(sum) //sum = 15 is equivalent to the effect of accumulation // There is also an Array.reduceRight() method corresponding to it, the difference is that this one operates from right to left

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Summary and recommendation of JavaScript array judgment methods
  • Let's learn about javascript array methods
  • Complete list of javascript array methods
  • Detailed explanation of the new array methods in JavaScript es6
  • Detailed explanation of 27 methods in javascript array

<<:  Why Seconds_Behind_Master is still 0 when MySQL synchronization delay occurs

>>:  Let you understand how HTML and resources are loaded

Recommend

Detailed explanation of Linux DMA interface knowledge points

1. Two types of DMA mapping 1.1. Consistent DMA m...

Detailed explanation of the relationship between Vue and VueComponent

The following case reviews the knowledge points o...

Fixed table width table-layout: fixed

In order to make the table fill the screen (the re...

How to implement data persistence using the vuex third-party package

Purpose: Allow the state data managed in vuex to ...

The simplest form implementation of Flexbox layout

Flexible layout (Flexbox) is becoming increasingl...

Solve the problem of Syn Flooding in MySQL database

Syn attack is the most common and most easily exp...

HTML table tag tutorial (20): row background color attribute BGCOLOR

The BGCOLOR attribute can be used to set the back...

About WSL configuration and modification issues in Docker

https://docs.microsoft.com/en-us/windows/wsl/wsl-...

How to change MySQL character set utf8 to utf8mb4

For MySQL 5.5, if the character set is not set, t...

JavaScript to implement dynamic digital clock

This article shares the specific code for impleme...

Summary of MySQL foreign key constraints and table relationships

Table of contents Foreign Key How to determine ta...

HTML checkbox Click the description text to select/uncheck the state

In web development, since the checkbox is small an...

19 MySQL optimization methods in database management

After MySQL database optimization, not only can t...