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

Founder font library Chinese and English file name comparison table

Founder Type Library is a font library developed ...

Detailed explanation of the use of $emit in Vue.js

1. Parent components can use props to pass data t...

Solution to CSS flex-basis text overflow problem

The insignificant flex-basis has caused a lot of ...

GZIP compression Tomcat and improve web performance process diagram

1. Introduction I recently worked on a project an...

Introduction to the role of HTML doctype

Document mode has the following two functions: 1. ...

Ubuntu Server 16.04 MySQL 8.0 installation and configuration graphic tutorial

Ubuntu Server 16.04 MySQL 8.0 installation and co...

Complete steps of centos cloning linux virtual machine sharing

Preface When a Linux is fully set up, you can use...

Calculation of percentage value when the css position property is absolute

When position is absolute, the percentage of its ...

Solve the problem of specifying udp port number in docker

When Docker starts a container, it specifies the ...

Box-shadow and drop-shadow to achieve irregular projection example code

When we want to add a shadow to a rectangle or ot...

How to manually upgrade the kernel in deepin linux

deepin and Ubuntu are both distributions based on...

MySQL 8.0.19 installation and configuration tutorial under Windows 10

I will be learning MySQL next semester. I didn...

Detailed explanation of React event binding

1. What is In react applications, event names are...

MySQL database case sensitivity issue

In MySQL, databases correspond to directories wit...