[ES6] These are the common ways to manipulate arrays.

Keywords: Attribute JSON REST Javascript

(1) Array creation

  1. How to use Array arrays
new Array();  // // Create an array
new Array([size]);  // Create an array and specify the length. Note that it's not the upper limit, it's the length.
new Array(element0, element1, ..., elementn);  // Create an array and assign values

const array = new Array();
array[0] = '1';
  1. The method of using literal quantity
const array = []; //Create an empty array
const array2 = [1, 2, 3]; //Create an array with three elements

(2) Array Attributes

constructor // Returns the prototype function that creates the array object
length // Returns the length of an array object
prototype // Prototype methods and attributes for arrays can be added

(3) Whether the detection is an array or not

  1. Using instanceof method

instanceof is used to determine whether a variable is an instance of an object?

const array = new Array();
array instanceof Array; //true
  1. Use the constructor attribute

The constructor attribute returns a reference to the array function that created the object, which is the constructor corresponding to the object.

const array = new Array();
array.constructor === Array; // true
  1. Using the isArray() method

For browsers that support isArray, the isArray method is used directly.

const array = new Array();
Array.isArray(array); //true

If the browser does not support Array.isArray(), the necessary judgment is required.

/**
 * Determine whether an object is an array, the parameter is not an object or an array, return false?
 *
 * @param {Object} arg You need to test whether it's an array object or not
 * @return {Boolean} The incoming parameter is that the array returns true, otherwise false
 */
function isArray(arg) {
    if (typeof arg === 'object') {
        return Object.prototype.toString.call(arg) === '[object Array]';
    }
    return false;
}

(4) Addition and deletion of array elements

  1. Array. push (e1, e2,... EN) adds one or more elements to the end of the array and returns the length of the new array.
const array = [1, 2, 3];
const length = array.push(4, 5);
// array: [1, 2, 3, 4, 5]; length: 5
  1. Array. unshift (e1, e2,... EN) adds one or more elements to the beginning of an array and returns the length of the new array.
const array = [1, 2, 3];
const length = array.unshift(4, 5);
// array: [ 4, 5, 1, 2, 3]; length: 5
  1. array.pop() deletes the last element from the array and returns the value of the last element. The last element of the original array is deleted. The array returns undefined in space-time.
const array = [1, 2, 3];
const poped = array.pop();  
// array: [1, 2]; poped: 3
  1. array.shift() deletes the first element of the array and returns the first element. The first element of the original array is deleted. The array is empty and returns undefined.
const array = [1, 2, 3];
const shifted = array.shift();  
// array: [2, 3]; shifted: 1
  1. array.splice(start[, deleteCount, item1, item2,...]) adds / deletes elements from the array. The return value is a new array of deleted elements. If only one element is deleted, the array containing only one element is returned. If no element is deleted, an empty array is returned.
  • Start specifies the start location of the modification (counted from 0). If it exceeds the length of the array, it adds content from the end of the array; if it is negative, it indicates the number of bits starting from the end of the array (counted from 1).
  • DeleteCount (optional), the number of elements to be deleted from the start location. If deleteCount is 0, the element is not removed. In this case, at least one new element should be added. If the deleteCount is greater than the total number of elements after the start, the elements after the start will be deleted (including the start bit).
  • item1, item2,... (Optional) To add elements to the array, start at the start location. If not specified, splice() will delete only array elements.
const array = [1, 2, 3, 4, 5];

const deleted = array.splice(2, 0, 6); // Insert 6 at index 2
// array becomes [1, 2, 6, 3, 4, 5]; deleted is []

(5) Interconversion of Arrays and Strings

  1. Array to string

array.join(separator=',') connects elements in an array to a string through a separator and returns the string, which defaults to ",".

const array = [1, 2, 3];
let str = array.join(',');
// str: "1,2,3"

toLocaleString(), toString(), valueOf(): Can be seen as a special use of join(), not commonly used.

  1. String Rotation Array

string.split(separator,howmany) is used to split a string into an array of strings.
separator (required), string or regular expression that partitions a string from the place specified by the parameter.
howmany (optional), which specifies the maximum length of the returned array.

let str = "abc,abcd,aaa";
let array = str.split(",");// Decomposition at each comma (,).
// array: [abc,abcd,aaa]

const array1 = "helloworld";
let str1 = s1.split('');  
//["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]

(6) Interception and merging of arrays

  1. Array interception - array.slice(start, end) method
  • slice() returns the start subscript from the array through the index position until the end subscript ends (excluding) in a new array. This method does not modify the original array, but returns a new subarray.
  • Start (mandatory), setting the starting position of the new array (subscripts start at 0); if negative, it means starting at the end of the array (- 1 refers to the last element, - 2 refers to the penultimate element, and so on).
  • End (optional), sets the end of the new array; defaults to the end of the array if this parameter is not filled in; if it is negative, it means starting at the end of the array (-1 refers to the last element, -2)
    Point to the penultimate element, and so on.
// Gets a subarray containing only the last element
let array = [1,2,3,4,5];
array.slice(-1); // [5]

// Gets a subarray that does not contain the last element
let array2 = [1,2,3,4,5];
array2.slice(0, -1); // [1,2,3,4]

This method does not modify the array, but returns a subarray. If you want to delete an element in an array, you should use the method array.splice().

  1. Combination of arrays - array. concat ([item1 [, Item2 [,.. [, itemN]]]]) method

conact() is to connect multiple arrays (or strings, or mixtures of arrays and strings) into an array and return a new connected array.

const array = [1,2].concat(['a', 'b'], ['name']);
// [1, 2, "a", "b", "name"]

(7) Sorting of Array Elements

  1. array.sort() method

The sort() method is used to sort the elements of an array and return the original array. If there are no parameters, sort them according to the sequence of UniCode codes.

const array = ['a', 'd', 'c', 'b'];
array.sort();  //['a', 'b', 'c', 'd']

Custom sorting can be achieved by passing in a sort() sorting rule function.

Sorting function rules: (1) pass two parameters; (2) when the return value is positive, exchange the position of the incoming two parameters in the array.

Sort by numerical size - ascend

[1, 8, 5].sort((a, b) => {
  return a-b; // Ranking from small to large
});
// [1, 5, 8]

Sort by numerical size - descend

[1, 8, 5].sort((a, b) => {
  return b-a; // Ranking from large to small
});
// [8, 5, 1]
  1. array.reverse() method
    The reverse() method reverses the position of the elements in the array. The first element becomes the last element and the last element becomes the first element. Operate on the original array, and then return to the original array.
let arr = [1,2,3,4,5]
console.log(arr.reverse())    // [5,4,3,2,1]
console.log(arr)    // [5,4,3,2,1]

The sort() and reverse() methods of the array modify the original array.

(8) Location of elements in arrays

  1. indexOf() and lastIndexOf()
  • The indexOf(searchElement[, fromIndex = 0]) method returns the first occurrence of a specified string value in the string.
  • The lastIndexOf(searchElement[, fromIndex = 0]) method returns the last occurrence of a specified string value, searching backwards and forwards for the specified position in a string.
  • Both methods take two parameters: searchElement: the element to be looked up; fromIndex: the index location to start looking up.
  • Both methods return the location of the lookup item in the array, or - 1 if it is not found.
[2, 9, 7, 8, 9].indexOf(9); // 1
[2, 9, 7, 8, 9].lastIndexOf(9); // 4
  1. find() and find index ()

(1) The call back [, thisArg]) method is used to find the first eligible array element. Its parameter is a callback function, which is executed by all group members in turn until the first member whose return value is true is found and then returned to that member. If there are no qualified members, undefined is returned.

[1, 4, -5, 10].find((n) => n < 0)
// -5

The callback function of the find() method can accept three parameters, namely the current value, the current position and the original array.

[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10

(2) findIndex(callback[, thisArg]) returns the location of the first eligible member of the array, and - 1 if all members are not eligible.

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2

Both methods accept the second parameter, which binds the callback function's this object.

function f(v){
  return v > this.age;
}
let person = {name: 'John', age: 20};
[10, 12, 26, 15].find(f, person);    // 26
  1. The include (searchElement [, fromIndex = 0]) method returns a Boolean value indicating whether an array contains a given value.

This method takes two parameters: searchElement: the element to be looked up; fromIndex: the index location to start looking up.

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true

(9) traversal and iteration of arrays

  1. The array.filter(callback, thisArg) method tests all elements using the specified function and creates a new array containing all elements that pass the test.

Description of parameters:

  • callback is a function used to test each element of an array, returning true to indicate that the element is retained (passed the test), while false does not.
  • This Arg is optional. The value used for this when calling back is executed.
// callback is defined as follows: element: current element value; index: current element subscript; array: current array
function callback(element, index, array) {
  // The callback function must return true or false, return true to retain the element, and false to retain it.
  return true || false;
}

const filtered = [1, 2, 3].filter(element => element > 1);
// filtered: [2, 3];
  1. The array.every(callback[, thisArg]) method detects whether every element in the array passes the callback test, all pass the true test, otherwise return false.
// callback is defined as: element: current element value; index: current element subscript; array: current array
function callback(element, index, array) {
  // The callback function must return true or false to tell every one if it passes the test
  return true || false;
}

let a = [1, 2, 3, 4, 5];
let b = a.every((item) => {
    return item > 0;
});
let c = a.every((item) => {
    return item > 1;
});
console.log(b); // true
console.log(c); // false
  1. array.some(callback[, thisArg]) determines whether an array contains elements that can be tested by callback, unlike every body, which returns true as long as an element passes the test. The callback definition is the same as above.
[2, 5, 8, 1, 4].some(item => item > 6);
// true
  1. The array.map(callback[, thisArg]) method returns a new array consisting of the return value of each element in the original array after calling the callback function.
let a = [1, 2, 3, 4, 5];

let b = a.filter((item) => {
    return item > 3;
});
console.log(b); // [4 ,5]

let bb = [];
a.map((item) => {
    if (item > 3) {
        bb.push(item);
    }
});
console.log(bb);    // [4, 5]

let bbb = a.map((item) => {
    return item + 1;
});
console.log(bbb);   // [2, 3, 4, 5, 6]
  1. array.forEach(callbak) executes the corresponding method for each element of the array.
// callback is defined as: element: current element value; index: current element subscript; array: current array

let a = [1, 2, 3, 4, 5];

let b = [];
a.forEach((item) => {
    b.push(item + 1);
});
console.log(b); // [2,3,4,5,6]
  1. Traversing arrays: entries(), values(), keys()

All three methods return a traversal object, which can be traversed by a for...of loop. The only difference is that keys() is the traversal of key names, values() is the traversal of key values, and entries() is the traversal of key value pairs.

for(let item of ['a','b'].keys()){
    consloe.log(item);
    //0
    //1
}
for(let item of ['a','b'].values()){
    consloe.log(item);
    //'a'
    //'b'
}
let arr4 = [0,1];
for(let item of arr4.entries()){
    console.log(item);  
    //  [0, 0]
    //  [1, 1]
}
for(let [index,item] of arr4.entries()){
    console.log(index+':'+item);
    //0:0
    //1:1
}
  1. The array. reduce (callback [, initial Value]) method returns the cumulative value generated by calling the callback function for each item of the array.
const total = [0, 1, 2, 3].reduce((sum, value) => {
  return sum + value;
}, 0);
// total is 6

const flattened = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => {
  return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]

Parameter description: initialValue: Accumulator initial value, callback function is defined as follows:

function callback(accumulator, currentValue, currentIndex, array) {
}

The accumulator represents the value of the accumulator in the callback parameter above. When initialized, if initialValue has a value, the accumulator initializes the value of initialValue, and the whole loop starts with the first element; if initialValue has no value, the accumulator initializes the value of the first element of the array, the current Value is the value of the second element of the array, and the whole loop starts with the second element. Start. The data type of initialValue can be of any type and does not need to be the same as the element value type in the original array.

const newArray = [{ name: 'aa', age: 1 }, { name: 'bb', age: 2 }, { name: 'cc', age: 3 }].reduce((arr, element) => {
  if (element.age >= 2) {
    arr.push(element.name);
  }
  return arr; 
  // There must be a return, because the return value of the return is assigned to the new accumulator, otherwise the value of the accumulator will be undefined.
}, []);
// newArray is ["bb", "cc"];

// The code above is equally written:
const newArray = [{ name: 'aa', age: 1 }, { name: 'bb', age: 2 }, { name: 'cc', age: 3 }].filter(element => element.age >= 2).map(item => item.name);
// newArray is ["bb", "cc"];

(10) Other methods

  1. Array.from() method

The Array.from() method is used to convert objects like arrays (objects with length attributes) and traversable objects into real arrays.
For example, using the Array.from(). method, you can easily convert the JSON array format to an array.

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
  1. Array.of() method

The Array.of() method is to convert a set of values into an array.

let arr0 = Array.of(1,2,33,5);
console.log(arr0);//[1,2,33,5]

let arr1 = Array.of('Hello','hello');
console.log(arr1);//["Hello," "hello"]

(11) Extended Operator

The spread operator is three points (...). It is like the inverse operation of rest parameters, which converts an array into a comma-separated sequence of parameters.

console.log(...[1, 2, 3])
// 1 2 3

console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5

This operator is mainly used for function calls.

function add(x, y) {
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42

Note that if the extension operator is enclosed in parentheses, the JavaScript engine will think that this is a function call and will report an error.

(...[1,2])
// Uncaught SyntaxError: Unexpected number

console.log((...[1,2]))
// Uncaught SyntaxError: Unexpected number

console.log(...[1, 2])
// 1,2

Posted by wildwobby on Wed, 20 Mar 2019 16:54:28 -0700