Common array operations in JavaScript

Common array operations in JavaScript

1. concat()

concat() method is used to concatenate two or more arrays. This method does not mutate the existing array, it simply returns a copy of the concatenated array.

var arr1 = [1,2,3];
var arr2 = [4,5];
var arr3 = arr1.concat(arr2);
console.log(arr1); //[1, 2, 3]
console.log(arr3); //[1, 2, 3, 4, 5]

2. join()

The join() method is used to put all the elements in an array into a string. The elements are separated by the specified separator, and the default separator is ',', which does not change the original array.

var arr = [2,3,4];
console.log(arr.join()); //2,3,4
console.log(arr); //[2, 3, 4]

3. push()

The push() method adds one or more elements to the end of an array and returns the new length. Adding at the end returns the length, which will change the original array.

var a = [2,3,4];
var b = a.push(5);
console.log(a); //[2,3,4,5]
console.log(b); //4

5. shift()

shift() method is used to remove the first element of an array and return the value of the first element. Returns the first element, mutating the original array.

var arr = [2,3,4];
console.log(arr.shift()); //2
console.log(arr); //[3,4]

6. unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length. Returns the new length, mutating the original array.

var arr = [2,3,4,5];
console.log(arr.unshift(3,6)); //6
console.log(arr); //[3, 6, 2, 3, 4, 5]

Tip: This method does not need to pass parameters. If no parameters are passed, no elements will be added.

7. slice()

slice() method returns a new array containing the elements in arrayObject from start to end (excluding this element). Returns the selected element. This method does not modify the original array.

var arr = [2,3,4,5];
console.log(arr.slice(1,3)); //[3,4]
console.log(arr); //[2,3,4,5]

splice()

splice() method removes zero or more elements starting at index and replaces the removed elements with one or more values ​​specified in the parameter list. If elements are deleted from arrayObject , an array containing the deleted elements is returned. splice() method modifies the array directly.

var a = [5,6,7,8];
console.log(a.splice(1,0,9)); //[]
console.log(a); // [5, 9, 6, 7, 8]
var b = [5,6,7,8];
console.log(b.splice(1,2,3)); //[6, 7]
console.log(b); //[5, 3, 8]

9. substring() and substr()

Similarities: If you only write one parameter, the functions of both are the same: both are to intercept the string fragment from the current subscript to the end of the string.

substr(startIndex);
substring(startIndex);
var str = '123456789';
console.log(str.substr(2)); // "3456789"
console.log(str.substring(2)) ;// "3456789"

Differences: The second parameter substr(startIndex,lenth): The second parameter is the length of the string to be intercepted (intercept a string of a certain length from the starting point); substring(startIndex, endIndex ): The second parameter is the final subscript of the string to be intercepted (intercept the string between 2 positions, 'including the head but not the tail').

console.log("123456789".substr(2,5)); // "34567"
console.log("123456789".substring(2,5)) ; // "345"

10. sort

Sort by Unicode code position, ascending by default

var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]

11. reverse()

The reverse() method is used to reverse the order of elements in an array. What is returned is the reversed array, which will change the original array.

var arr = [2,3,4];
console.log(arr.reverse()); //[4, 3, 2]
console.log(arr); //[4, 3, 2]

12. indexOf and lastIndexOf

Both indexOf and lastIndexOf accept two parameters: the value to be searched and the starting position to be searched. If the value does not exist, -1 is returned; if the value does exist, the starting position is returned. indexOf searches from the front to the back, and lastIndexOf searches from the back to the front. indexOf

var a = [2, 9, 9];
a.indexOf(2); // 0
a.indexOf(7); // -1
 
if (a.indexOf(7) === -1) {
 // element doesn't exist in array
}
lastIndexOf
 
var numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2); // 3
numbers.lastIndexOf(7); // -1
numbers.lastIndexOf(2, 3); // 3
numbers.lastIndexOf(2, 2); // 0
numbers.lastIndexOf(2, -2); // 0
numbers.lastIndexOf(2, -1); // 3

13. every pair array

every runs the given function on each item in the array, and returns ture if each item returns true

function isBigEnough(element, index, array) {
 return element < 10;
} 
[2, 5, 8, 3, 4].every(isBigEnough); // true

14. some

some runs the given function on each item in the array, and returns ture if any of them returns true

function compare(element, index, array) {
 return element > 10;
}  
[2, 5, 8, 1, 4].some(compare); // false
[12, 5, 8, 1, 4].some(compare); // true

15. Filter

filter runs the given function on each item in the array, returning an array of items whose result is ture .

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];
var longWords = words.filter(function(word){
 return word.length > 6;
});
// Filtered array longWords is ["exuberant", "destruction", "present"]

16. Map

Runs the given function on each item in an array, returning a new array consisting of the results of each function call.

var numbers = [1, 5, 10, 15];
var doubles = numbers.map(function(x) {
  return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]

17. forEach array traversal

const items = ['item1', 'item2', 'item3'];
const copy = [];  
items.forEach(function(item){
 copy.push(item)
});

ES6 adds new methods for operating arrays

1. find():

Pass a callback function to find the first element in the array that matches the current search criteria, return it, and terminate the search.

const arr = [1, "2", 3, 3, "2"]
console.log(arr.find(n => typeof n === "number")) // 1

2. findIndex():

Pass a callback function to find the first element in the array that matches the current search criteria, return its index, and terminate the search.

const arr = [1, "2", 3, 3, "2"]
console.log(arr.findIndex(n => typeof n === "number")) // 0

3. fill():

Replace the elements in the array with new elements. You can specify the replacement subscript range.

arr.fill(value, start, end)

4. copyWithin():

Select an index of the array and start copying the array elements from that position. The default is to start copying from 0. You can also specify a range of elements to copy.

arr.copyWithin(target, start, end)
const arr = [1, 2, 3, 4, 5]
console.log(arr.copyWithin(3))
 // [1,2,3,1,2] starts from the element with index 3 and copies the array, so 4 and 5 are replaced by 1 and 2
const arr1 = [1, 2, 3, 4, 5]
console.log(arr1.copyWithin(3, 1)) 
// [1,2,3,2,3] starts from the element with index 3 and copies the array. The index of the first element to be copied is 1, so 4 and 5 are replaced by 2 and 3.
const arr2 = [1, 2, 3, 4, 5]
console.log(arr2.copyWithin(3, 1, 2)) 
// [1,2,3,2,5] starts from the element with index 3 and copies the array. The first element to be copied is index 1 and the end position is 2, so 4 is replaced by 2.

5. from

Convert array-like object and iterable objects to real arrays

const bar = ["a", "b", "c"];
Array.from(bar);
// ["a", "b", "c"]
 
Array.from('foo');
// ["f", "o", "o"]

6. of

Used to convert a set of values ​​into an array. The main purpose of this method is to make up for the shortcomings of the array constructor Array() . Because of the different number of parameters, the behavior of Array() will be different.

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
Array(7); // [ , , , , , , ]
Array(1, 2, 3); // [1, 2, 3]

7. entries() returns an iterator: returns key-value pairs

//array const arr = ['a', 'b', 'c'];
for(let v of arr.entries()) {
 console.log(v)
}
// [0, 'a'] [1, 'b'] [2, 'c']
 
//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.entries()) {
 console.log(v)
}
// ['a', 'a'] ['b', 'b'] ['c', 'c']
 
//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.entries()) {
 console.log(v)
}
// ['a', 'a'] ['b', 'b']

8. values() returns an iterator: returns the value of the key-value pair

//array const arr = ['a', 'b', 'c'];
for(let v of arr.values()) {
 console.log(v)
}
//'a' 'b' 'c'
 
//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.values()) {
 console.log(v)
}
// 'a' 'b' 'c'
 
//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.values()) {
 console.log(v)
}
// 'a' 'b'

9. keys() returns an iterator: returns the key of the key-value pair

//array const arr = ['a', 'b', 'c'];
for(let v of arr.keys()) {
 console.log(v)
}
// 0 1 2
 
//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.keys()) {
 console.log(v)
}
// 'a' 'b' 'c'
 
//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.keys()) {
 console.log(v)
}
// 'a' 'b'

10. includes

Determines whether the element exists in the array. Parameters: the value to be searched, the starting position. This can replace indexOf judgment method in ES5 era. indexOf determines whether an element is NaN , which will result in an error.

var a = [1, 2, 3];
a.includes(2); // true
a.includes(4); // false

This is the end of this article about commonly used array operation methods in JavaScript. For more relevant JavaScript array operation methods, 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!

You may also be interested in:
  • Detailed explanation of how to create an array in JavaScript
  • Detailed explanation of the new array methods in JavaScript es6
  • Detailed explanation of JS array methods
  • Detailed explanation of common methods of JavaScript arrays
  • Summary of several common methods of JavaScript arrays
  • Commonly used JavaScript array methods
  • Detailed Example of JavaScript Array Methods

<<:  Nginx URL rewriting mechanism principle and usage examples

>>:  Mysql implementation of full-text search and keyword scoring method example

Recommend

Vue implements anchor positioning function

This article example shares the specific code of ...

How to build a drag and drop plugin using vue custom directives

We all know the drag-and-drop feature of HTML5, w...

Detailed explanation of the process of zabbix monitoring sqlserver

Let's take a look at zabbix monitoring sqlser...

Detailed explanation of the role of key in React

Table of contents Question: When the button is cl...

Complete steps to install MySQL 8.0.x on Linux

MySQL Introduction to MySQL MySQL was originally ...

Detailed explanation of the role of brackets in AngularJS

1. The role of brackets 1.1 Square brackets [ ] W...

How to install jupyter in docker on centos and open ports

Table of contents Install jupyter Docker port map...

Detailed explanation of long transaction examples in MySQL

Preface: The "Getting Started with MySQL&quo...

Open the app on the h5 side in vue (determine whether it is Android or Apple)

1. Development environment vue+vant 2. Computer s...

MySQL log system detailed information sharing

Anyone who has worked on a large system knows tha...

Detailed explanation of the process of installing msf on Linux system

Or write down the installation process yourself! ...

Sample code for implementing follow ads with JavaScript

Floating ads are a very common form of advertisin...

How InnoDB implements serialization isolation level

Serialization implementation InnoDB implements se...