Summarize your common array methods

forEach() method

The given function is executed once for each element of the array

Receive two parameters. Here, we usually only receive one parameter

arr[abc,cba,bbc]

forEach(fuction(item,index,arr))

The first parameter: item means the array element is required

For example, abc

Index refers to the index (optional)

For example, abc index 0

arr is the array ontology of execution

       const fruits = ["Banana", "Orange", "Apple", "Mango"];
        fruits.forEach(function(item,index,arr){
            console.log(item);
            console.log(index);
            console.log(JSON.stringify(arr));
        })
        console.log(fruits);

map() method

Create a new array, which consists of the return value after each element in the original array calls the provided function once.

It is very similar to forEach above. The biggest difference is that forEach directly returns the original array. Here, it returns the new array

The same is true for map(), which executes the given function once for each element of the array

map(fuction(item,index,arr))

item refers to the array element and is required

For example, abc

Index refers to the index (optional)

For example, abc index 0

arr is the array ontology of execution

    const array = [1,3,5,7,9]
        const map1 = array.map(function(x)
        {
            if(x > 3)
            {
              return x 
            }
        })
        console.log(map1); //[undefined,undefined,5,7,9]

Split method

This is to convert the string into an array

console.log(reformattedArray)
//Split each character, including spaces
var a = "Hello world"
const abc = a.split('');
console.log(abc);
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']


var str="How are you doing today?";
var n=str.split(" ",3);
//How,are,you n output three letter words

//Use one character as the separator:
var str="How are you doing today?";
var n=str.split("o");
H,w are y,u d,ing t,day?

pop() method

Deleting the last attribute of the array and returning it will change the original array

 consconst plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
 console.log(plants.pop()); // expected output: "tomato" 
 console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

shift method

Delete the first property of the array and return it

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1); //[2,3]

console.log(firstElement);[1]

unshift method

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

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

splice method

var a = ['a','b','c']
var b = a.splice(1,1,'e','f')
console.log(a);//A is the operated [a,e,f,c] of the original array
console.log(b); //B is the return value and the array element to be replaced. This method will change the original array [b]

// splice(start,deletecount,item)
// Start: start position
// deletecount: deletes the number of digits
// Item: replaced item
// The return value is the deleted string
// If there are additional parameters, the item will be inserted at the location of the removed element.
// Splice: remove. The splice method removes one or more arrays from the array and replaces them with new item s.
// Take a simple example 
// Here is the slice method
var arr = [1,2,3,4,5,6,7]
console.log(arr.slice(3)); //[4,5,6,7] intercept from the third one. Because end is not given, all are truncated. arr=[1,2,3]
console.log(arr.slice(0,3));//[] from 0 to 3, but you can understand it as [) [1,2,3] in mathematics
console.log(arr.slice(0,-2));  //  [1,2,3,4,5] a negative number is the penultimate number. Here, - 2 is the penultimate number
console.log("Deleted:", a.splice(1, 0, 2, 2)) //The second number inserted is 0, which means 0 is deleted  
console.log("a Array elements:", a) //1,2,2,2,3,4,5,6,7

Personal summary: if the slice parameter is positive, it will be counted from left to right; if it is negative, it will be counted from right to left,

The intercepted array is consistent with the direction of the number. If there are 2 parameters, the intercepted array is the intersection of the number. If there is no intersection, an empty array is returned

slice can also cut strings. The usage is the same as array, but it should be noted that spaces are also characters

concat method

A simple understanding is to merge strings

A string. concat(B string)

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);[a,b,c,d,e,f]

Note that the slice method, concat method and split method above can convert a class array into an array

arr.indexOf(searchElement[, fromIndex]) can pass two parameters. The first parameter must be the element you want to find. The second parameter is the location you want to find

indexof method

It's very simple. The index is the subscript

Enter an element. If there is one, the subscript of the element is not returned (- 1)

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

Include() method

It is used to determine whether an array contains a specified value. If it does, it returns true; otherwise, it returns false.

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

find() method

Returns the value of the first element in the array that satisfies the provided test function. Otherwise, it returns undefined. Remember, it's the first one

const array1 = [5,12,8,130,44]
const found = array1.find(function(item){
    if(item > 6 )
    {
        return item
    }
})
console.log(found);//12

filter()

Method creates a new array containing all the elements of the test implemented by the provided function.

The filter() function receives a function as its parameter. The element with the return value of "true" will be added to the new array. The element with the return value of "false" will not be added to the new array. Finally, the new array will be returned. If there is no qualified value, an empty array is returned

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
expected output: Array ["exuberant", "destruction", "present"]

findIndex() method

Method returns the first qualified index in the array. If it is not found, it returns - 1, which is similar to the above

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = function(item)
{
    if(item > 13)
    {
        return item
    }

}

console.log(array1.findIndex(isLargeNumber));
expected output: 3

sort() method

Method sorts the elements of the array using the in place algorithm and returns the array. The default sort order is built when converting elements to strings and then comparing their sequence of UTF-16 code unit values

//It feels like grammar sugar

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);['Dec', 'Feb', 'Jan', 'March']
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
expected output: Array [1, 100000, 21, 30, 4] //Unicode sort

arr.sort([compareFunction])
If omitted: compareFunction´╝îElement according to the value of each character of the converted String Unicode Sites were sequenced.
So inside compareFunction In fact, a
 So you can't sort numbers

reverse() method

Method inverts the positions of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method will change the original array

The original array will be changed directly

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

reduce method

The reduce() method executes a reducer function provided by you for each element in the array in order. Each time the reducer is run, the calculation results of the previous elements will be passed in as parameters, and finally the results will be summarized into a single return value.

Explore the feeling of accumulation and decrement of all points

There are two parameters. The first parameter and the second parameter are optional

The first argument is a function

Here we call the "reducer" function

This function also has four parameters

  • previousValue: the return value of the last call to callbackFn. In the first call, if the initial value initialValue is specified, its value is initialValue; otherwise, it is the element array[0] with the array index of 0.
  • currentValue: the element being processed in the array. In the first call, if the initial value initialValue is specified, its value is the element array[0] with the array index of 0; otherwise, it is array[1].
  • currentIndex: the index of the element being processed in the array. If the initial value initialValue is specified, the starting index number is 0; otherwise, it starts from index 1.
  • Array: an array used for traversal.
    var numbers = [65, 44, 12, 4];
    var cc 
    function getSum(total, num) {
        return total - num;
    }
    cc = numbers.reduce(getSum)
    console.log(cc); //5

Similarly, this reducer function can be customized, and its main purpose is to achieve a repeated purpose, giving me a feeling of summing up the high school equal difference and equal ratio sequence

The main function of the reduce() function is to perform accumulation processing, that is, to receive a function as an accumulator, to execute the accumulator from left to right for each element in the array, and to return the final processing result.

 

Posted by phpcodec on Fri, 12 Aug 2022 02:21:05 +0930