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

Vue uses filters to format dates

This article example shares the specific code of ...

Detailed explanation of how to use the mysql backup script mysqldump

This article shares the MySQL backup script for y...

How to elegantly back up MySQL account information

Preface: I recently encountered the problem of in...

About front-end JavaScript ES6 details

Table of contents 1. Introduction 1.1 Babel Trans...

Implementing shopping cart function based on vuex

This article example shares the specific code of ...

MySQL database case sensitivity issue

In MySQL, databases correspond to directories wit...

Use javascript to create dynamic QQ registration page

Table of contents 1. Introduction 1. Basic layout...

Vue2.x - Example of using anti-shake and throttling

Table of contents utils: Use in vue: explain: Ima...

This article helps you understand PReact10.5.13 source code

Table of contents render.js part create-context.j...

The latest 36 high-quality free English fonts shared

01. Infinity Font Download 02. Banda Font Download...

How to use lazy loading in react to reduce the first screen loading time

Table of contents use Install How to use it in ro...

How to invert the implementation of a Bezier curve in CSS

First, let’s take a look at a CSS carousel animat...

Overview of the definition of HTC components after IE5.0

Before the release of Microsoft IE 5.0, the bigges...