JS array common operations

Time:2022-7-25

Array

Each slot of ECMAScript array can store any type. At the same time, it is also dynamic and grows automatically.

1. Create an array

let colors = new Array();
let colors2 = [];  // literal quantity

let colors3 = new Array(3);  // Initialization length
let names = new Array("Greg");  // Contains an element

let values1 = new Array("red", "blue", "green");
let values2 = [1,2,3,];  // It contains three elements: 1, 2 and 3

2. Array. From() and array. Of()

From () is used to convert a class array structure into an array instance, and of () is used to convert a set of parameters into an array instance.

  • Array.from()The first parameter of is an array like object, namelyAny structure that can be iterated, or has a length attribute and indexable elements

    For example: string, map, set, array (shallow copy), symbol The object of the iteratorargumentsObjectBuilt in iterator object (also implements iterator interface)

    console.log(Array.from("Matt")); // ["M", "a", "t", "t"]
    
    const m = new Map().set(1, 2).set(3, 4);
    console.log(Array.from(m)); // [[1, 2], [3, 4]]
    
    //The arguments object can be easily converted to an array
    function getArgsArray() {
    	return Array.from(arguments);
    }
    console.log(getArgsArray(1, 2, 3, 4)); // [1, 2, 3, 4]

    Array. From () also receives a second optional mapping function parameter, this function can directly enhance the value of the new array. You can also receive a third optional parameter that specifies the value of this in the mapping function.

    const a1 = [1, 2, 3, 4];
    const a2 = Array.from(a1, x => x**2);
    const a3 = Array.from(a1, function(x) {return x**this.exponent}, {exponent: 2});
    //Arrow function cannot be used here
    console.log(a2); // [1, 4, 9, 16]
    console.log(a3); // [1, 4, 9, 16]

  • Array.of()You can convert a set of parameters into an array. Used instead of the following

    function getArgsArray() {
    	return Array.prototype.slice.call(arguments);
        //return Array.from(arguments);
    }
    console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4]
    console.log(Array.of(undefined)); // [undefined]

3. Array vacancy

const options = [,,,,,]; //  Create an array containing 5 elements
console.log(options.length); // 5
console.log(options); // [,,,,,]

The new method of ES6 will treat vacancies asundefinedIncluding: for of, array. From(), array. Of()

The method before ES6 has other behaviors

const options = [1,,,,5];
//Map () skips empty positions
console.log(options.map(() => 6)); // [6, undefined, undefined, undefined, 6]
//Join() treats the empty position as an empty string
console.log(options.join('-')); // "1----5"

To avoid behavioral differences, explicit undefined can be used instead of empty bits

4. Index

If you use an index that exceeds the maximum index, the array length will automatically expand to the input index.

The length attribute is not read-only. You can delete or add elements by modifying the length attribute. If you add, it will be filled with undefined.

5. Detection array

//1. Generally valid
if (value instanceof Array){
//Operation array
}

//2. Recommended
if (Array.isArray(value)){
//Operation array
}

6. Iterator method

The prototype of array has three methods for retrieving the contents of the array:
keys()values()andentries()。 Keys () returns the iterator of the array index, values () returns the iterator of the array element, and entries () returns the iterator of the index / value pair

const a = ["foo", "bar", "baz", "qux"];
//Because these methods all return iterators, their contents can be
//Directly convert to an array instance through array. From()
const aKeys = Array.from(a.keys());
const aValues = Array.from(a.values());
const aEntries = Array.from(a.entries());
console.log(aKeys); // [0, 1, 2, 3]
console.log(aValues); // ["foo", "bar", "baz", "qux"]
console.log(aEntries); // [[0, "foo"], [1, "bar"], [2, "baz"], [3, "qux"]]

Deconstruction can split the key / value pairs produced by the entries () iterator in the loop

const a = ["foo", "bar", "baz", "qux"];
for (const [idx, element] of a.entries()) {
	console.log(idx);
	console.log(element);
}
// 0
// foo
//...

7. Copy and fill

  • The fill() fill function receives three parameters: fill content, start index (optional default 0), and end index (optional default to the tail)

    const zeroes = [0, 0, 0, 0, 0];
    zeroes.fill(6, 3);
    console.log(zeroes); // [0, 0, 0, 6, 6]
    zeroes. fill(0); //  Reset

  • Copywithin() performs shallow copying inside the array, and receives three parameters: the position to paste, the position to start copying (optional default 0), and the position to end copying (optional default to the end)

    ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    ints. copyWithin(2, 0, 6); //  Copy the elements between 0-5 and paste them into the space starting from index 2
    console.log(ints); // [0, 1, 0, 1, 2, 3, 4, 5, 8, 9]

8. Convert to string

Tostring(), tolocalestring() return comma separated strings formed by splicing the conversion strings of each element by the corresponding method.

join()Method receives a parameter as a separator (optional, default is comma)

let colors = ["red", "green", "blue"];
console.log(colors.join(",")); // red,green,blue
console.log(colors.join("||")); // red||green||blue

Note: if an item in the array is null or undefined, the empty string will be specially treated during conversion(“”)Representation

9. Stack and queue method

  • push()Method receives any number of parameters, adds them to the end of the array, and returns the length of the array
  • pop()Method is used to delete the last item of the array, reduce the length value of the array, and return the deleted item
  • shift()Method, which deletes the first item of the array and returns it, and then decreases the length of the array by 1.
  • unshift()Method adds any number of values at the beginning of the array, and then returns the new array length.

10. Sorting

  • The reverse () method reverses the original array elements

  • The sort () method arranges the elements in ascending order by default. First call string () for each item, and then in dictionary order. In most cases, this does not get the desired result,
    For this, sort () can receive a comparison function. The comparison function receives two parameters. If the first parameter should be in front of the second parameter, it returns a negative value, and so on.

    let values = [0, 1, 5, 10, 15];
    //Pass a descending function
    values.sort((a, b) => a < b ? 1 : a > b ? -1 : 0); 
    console.log(values); // 15,10,5,1,0

    If the element is only an array ascending function, it can also be written like this

    function compare(value1, value2){
    	return value2 - value1;
    }

11. Operation method

  • The concat () method returns thecopy(flatten). If the parameter is not an array, it is directly added to the array.

  • Slice() intercept function returnscopyMethod receives two parameters: start index (optional default 0), end index (excluding, optional default to tail)

  • The splice () method modifies the original array to receive three parameters: insert or delete position, delete quantity, elements to be added (optional) and returns an array composed of deleted elements

    let colors = ["green", "yellow", "orange", "blue"];
    removed = colors.splice(1, 1, "red", "purple");
    //Insert two values and delete an element
    alert(colors);
    // green,red,purple,orange,blue
    alert(removed);
    //Yellow, an array with only one element

12. Search method

  • Indexof(), lastindexof() and includes() all implement strict equality (= =), and both support setting the starting search position. The first two return indexes, and includes returns Boolean values

  • Find() and findindex() receive an assertion function. The assertion function receives three parameters: element, index and array itself. The assertion function returns a true value, indicating that the search stops at the same time
    You can also receive the second parameter to specify the internal this of the assertion function. These two methods return the first matching element and index respectively.

    const people = [
    	{
    		name: "Matt",
    		age: 27
    	},
    	{
    		name: "Nicholas",
    		age: 29
    	}
    ];
    console.log(people.find((element, index, array) => element.age < 28));
    // {name: "Matt", age: 27}
    console.log(people.findIndex((element, index, array) => element.age < 28));
    // 0

13. Iterative method

ECMAScript defines five iterative methods for arrays. Each method receives two parameters: the function running with each item as a parameter, and the optional scope object as the function running context (which affects the value of this in the function).The function passed to each method receives three parameters: array elements, element indexes, and the array itself

  • Every (): if true is returned for each function, true is returned.
  • Filter (): an array of elements whose return function returns true.
  • Foreach (): call the function only for each item, and there is no return value.
  • Map (): call the function for each item and return an array composed of the call results.
  • Some (): if an element returns true after calling the function, it returns true.

14. Merging method

The merging direction of reduce () and reduceright () methods is different. Both methods iterate over all the items of the array and build a final return value.
Both methods accept two parameters: the merge function, optionally as the initial value of the merge start point. Merge receives four parameters: the previous merge value, the current item, the index of the current item, and the array itself. The return value of the function will be the first parameter of the next call. If the second parameter (as the merging starting point value) is not passed into these two methods, the first iteration will start from the second item of the array, so the first parameter passed to the merging function is the first item of the array, and the second parameter is the second item of the array.

//Using merge accumulate array
let values = [1, 2, 3, 4, 5];
let sum = values.reduce((prev, cur, index, array) => prev + cur);
console.log(sum); // 15