Common Methods of JavaScript Arrays


foreword

Arrays are one of the most common data types in programming development. We mainly introduce some built-in methods and


First, the value in the array

Value specifies the position element value

According to the specified subscript corresponding to the array, the value of the element at the specified position can be obtained.

const arr = new Array("js","JavaScript","jQuery");
const first = arr[0] // 因为数组下标是从 0 开始算的
const two = arr[1]
const end = arr[arr.length-1]
console.log(first); // js
console.log(two); // JavaScript
console.log(end); // jQuery

Get the last element value

  • JavaScript pop() method to delete the last element (use with caution, it will change the original array)
let arr = new Array("js","JavaScript","jQuery");
const end = arr.pop()
console.log(end); // jQuery
console.log(arr); // ["js", "JavaScript"]
  • The JavaScript slice() method intercepts the specified range and returns an array
const arr = new Array("js","JavaScript","jQuery");
const end = arr.slice(-1); // -1 即取值最后一位
console.log(end); // ["jQuery"]
// 如果想取第二位则
const two = arr.slice(1, 2); // 即取值 从下标 1 (包含)开始到下标 2 之前(不含)内容
console.log(two); // ["JavaScript"]

Second, the method of changing the array itself

The method of actually changing the array itself is basically or the method will be like this

N elements are added at the end of push()

Adds one or more elements to the end of an array and returns the new length of the array.

let arr = ['a', 'b', 'c'];
const ele = arr.push('d');
console.log(ele); // 4
console.log(arr); // ['a','b','c','d']

pop() removes an element at the end

Removes the last element from the array and returns the value of that element. Returns undefined if the array is empty.

let arr = ['a', 'b', 'c', 'd'];
const ele = arr.pop();
console.log(ele); // 'd'
console.log(arr); // ['a','b','c']

shift() removes the first element

Removes the first element from the array and returns the value of that element.

let arr = ['a', 'b', 'c', 'd'];
const ele = arr.shift();
console.log(ele); // 'a'
console.log(arr); // ['b''c','d']

unshift() adds N elements at the first place

Adds one or more elements to the beginning of an array and returns the new length of the array.

var arr = ['a', 'b', 'c'];
var ele = arr.unshift('d'); // 可传多个参数
console.log(ele); // 4
console.log(arr); // ['d','a','b','c']

splice() deletes or adds N elements at the specified position

splice(start,deleteCount?,item1?) Modify the array by deleting or replacing existing elements or adding new elements in place, and return the modified content in the form of an array (if only one element is deleted, the return contains only one Array of elements. Returns an empty array if no elements were removed).

  • start: Specifies the starting position of the modification (counting from 0). If the length of the array is exceeded, the content is added from the end of the array; if it is a negative value, it indicates the number from the end of the array (counting from -1, which means -n is the last nth element and etc. equal to array.length-n); if the absolute value of the negative number is greater than the length of the array, it means that the starting position is the 0th position.
  • deleteCount (optional): an integer indicating the number of array elements to be removed.
  • If deleteCount is greater than the total number of elements after start, all elements after start will be deleted (including the start bit).
  • If deleteCount is omitted, or its value is greater than or equal to array.length - start (that is, if it is greater than or equal to the number of all elements after start), then all elements of the array after start will be deleted.
  • If deleteCount is 0 or negative, no elements are removed. In this case, at least one new element should be added.
  • item1, item2, … (optional): The elements to add to the array, starting from the start position. If not specified, splice() will only remove array elements.
var arr = ['a', 'b', 'c', 'd'];
// 从索引 2 的位置开始删除 0 个元素,插入"e"
var insertOnce = arr.splice(2, 0, 'e');
console.log(insertOnce); // []
console.log(arr); // ['a', 'b', 'e', 'c', 'd']
// 从索引 3 的位置开始删除一个元素
var delOnce = arr.splice(3, 1);
console.log(delOnce ); // ['c']
console.log(arr); // ['a', 'b', 'e', 'd']

sort() sorts an array

Sorts the elements of an array.

let arr = [1, 5, 2, 4, 3];
arr.sort();
arr.sort((a, b) => a - b); // 正序 arr.sort(function(a,b){return a -b})
console.log(arr); // [1,2,3,4,5]
arr.sort((a, b) => b - a); // 倒序 arr.sort(function(a,b){return b-a})
console.log(arr); // [1,2,3,4,5]
// or
let arr1 = [
    {
    
     name: 'Edward', age: 21 },
    {
    
     name: 'Sharpe', age: 37 },
    {
    
     name: 'And', age: 45 },
    {
    
     name: 'The', age: -12 },
    {
    
     name: 'Magnetic', age: 15 },
    {
    
     name: 'Zeros', age: 37 }
];
//依据age排序
arr1.sort(function (a, b) {
    
    
    return (a.age - b.age)
});
console.log(arr1); // [1,2,3,4,5]

reverse() Reversal operation is position reversal

Reverses the positions of the elements in an array and returns the array. The first element of the array becomes the last, the second element becomes the second-to-last... the last element of the array becomes the first.

var arr = [1, 2, 3, 4, 5];
arr.reverse();
// arr数组被修改: [5,4,3,2,1]
console.log(arr); // [5,4,3,2,1]

3. The method that does not change the array itself

slice() intercepts the specified range of elements

slice(begin?, end?) returns a new array object, which is a deep copy of the original array determined by begin and end (including begin, excluding end), both parameters are optional, this method That is, the value in the specified position is intercepted.

  • begin Optionally extract the starting index (starting from 0), from which the original array elements are extracted
  • If the parameter is negative, it means to extract from the penultimate element in the original array, and slice(-2) means to extract from the penultimate element to the last element (including the last element) in the original array.
  • If begin is omitted, the slice starts at index 0.
  • If begin is outside the index range of the original array, an empty array will be returned.
  • end Optional The index (starting from 0) at which the extraction ends, at which the extraction of the original array elements ends. slice will extract all elements in the original array with indexes from begin to end (begin is included, but end is not included).
  • slice(1,4) will extract all elements from the second element to the fourth element in the original array (elements with indices 1, 2, 3).
  • If this parameter is a negative number, it means that the last few elements in the original array will end the extraction. slice(-2,-1) indicates that the second-to-last element to the last element in the original array is extracted (excluding the last element, that is, only the second-to-last element).
  • If end is omitted, the slice will be extracted until the end of the original array.
  • If end is greater than the length of the array, slice will also be extracted to the end of the original array.
const arr = ['a', 'b', 'c', 'd'];
const res = arr.slice(0, 2);
console.log(arr); // ['a', 'b', 'c', 'd']
console.log(res); // ['a', 'b']

concat() merges N arrays

Merges two or more arrays. This method does not alter the existing array, but returns a new array. Even if the arrays before merging have the same value, they will not be deduplicated.

const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = ['e', 'f']
const arr3 = arr1.concat(arr2);
console.log(arr3 ); // ['a', 'b', 'c', 'd','e','f']

join() Get the specified delimiter string, the default ,split

Concatenates all elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, then that item will be returned without a separator (',' is used by default, if "" is used, there will be no characters between all elements).

const arr = ['a', 'b', 'c', 'd'];
const str = arr.join("-");
console.log(str); // "a-b-c-d"

forEach() traverses the array, generally used when doing comparisons or when each element has different processing logic

forEach(function(currentValue, index?, array?), thisValue?) Executes the given function once for each element of the array. currentValue Mandatory The value of the current element index Optional The index value of the current element array Optional The array object that the current element belongs to thisValue Optional The value is used as this when executing the callback function. If it is omitted or null or undefined is passed in, then the this of the callback function is the global object}

/**
 * @param {*} element 当前元素值
 * @param {*} index 下标
 * @param {*} array 当前数组
 */
const logArrayElements = (element, index, array) => {
    
    
    console.log('a[' + index + '] = ' + element, array);
}

// 注意索引 2 被跳过了,因为在数组的这个位置没有项
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

map() traverses the array, modifies the value of the corresponding element, and returns a new array

map(function(currentValue, index?, array?), thisValue?)
How does map() work? In fact, each element of the array is traversed once, and a new value is returned at the same time. Remember that the length of the returned data is the same as the length of the original array.

That is, creates a new array whose result is that each element in the array is the return value of one call to the provided function.

const kvArray = [{
    
     key: 1, value: 10 },
{
    
     key: 2, value: 20 },
{
    
     key: 3, value: 30 }];

const reformattedArray = kvArray.map(function (obj) {
    
    
    var rObj = {
    
    };
    rObj[obj.key] = obj.value;
    return rObj;
});
console.log(reformattedArray); // [{1: 10}, {2: 20}, {3: 30}]
console.log(kvArray); // 不变

filter() Filter specified condition elements

filter(function(currentValue,index,arr), thisValue)
creates a new array whose elements are checked by checking all elements in the specified array that meet the criteria.

That is, if the callback function returns true, this element will appear in the returned array, and if it returns false, it will not appear in the returned array

/**
 * 筛选出字符串数组中长度大于6的字符串
 */
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result); // ["exuberant", "destruction", "present"]

every() Determines whether the elements in the array meet the specified conditions

every(function(currentValue,index,arr), thisValue) tests whether all elements in an array can pass the test of a specified function. It returns a boolean value, if an empty array is received, this method will return true in all cases.

/*
 * 检查是否数组中的所有数字都小于40
 */
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold)); // true

some() Determines whether the elements in the array have the value of the specified condition

some(function(currentValue,index,arr), thisValue) tests whether at least 1 element in the array passes the provided function test. It returns a Boolean value, and if tested with an empty array, it returns false in any case.

/**
 * 检测数组中是否至少有一个数字大于 18:
 */
const ages = [3, 10, 18, 20];
function checkAdult(age, index, arr) {
    
    
    return age >= 18;
}
console.log(ages.some(checkAdult))

find() finds the first element value that meets the specified conditions

find(function(currentValue,index,arr), thisValue) returns the value of the first element in the array that satisfies the provided test function. Otherwise returns undefined.

/**
 * 获取数组中第一个大于10的值
 */
const array2 = [5, 12, 8, 130, 44];
const found = array2.find(element => element > 10);
console.log(found); // 12

flat() Array flattening, which can be flattened according to the depth of input parameters

flat(depth?) Traverses the array recursively according to a specified depth, and combines all elements with the elements in the traversed subarray into a new array and returns.

/**
 * depth 可选 指定要提取嵌套数组的结构深度,默认值为 1。
 */
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat()); // [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2)); // [0, 1, 2, [3, 4]]

new Set() combined with class array, deduplication

Array deduplication, new Set() generation, combined with the Array.from() static method to create a new shallow copy array from iterable or array-like objects

/**
 * 去重
 */
const getReplace = [0, 1, 5, 2, 1, 2, 6, 5, 2, 8];
console.log(new Set(getReplace)); // [0, 1, 5, 2, 6, 8]
console.log(Array.from(new Set(getReplace))); // [0, 1, 5, 2, 6, 8]
Array.prototype.removeDuplicate = function () {
    
    
    return Array.from(new Set(this));
};
console.log([1, 2, 1, 2, 3].removeDuplicate());

reduce() can return the data processed by the specified logic, such as returning the accumulated value or finding the value of the specified condition

You can intuitively return a value or object specified in the array, you can calculate the cumulative value of a property in the object and find the largest or smallest data, etc.

const pilots = [
    {
    
    
        id: 10,
        name: "Poe Dameron",
        years: 14,
    },
    {
    
    
        id: 2,
        name: "Temmin 'Snap' Wexley",
        years: 30,
    },
    {
    
    
        id: 41,
        name: "Tallissan Lintra",
        years: 16,
    },
    {
    
    
        id: 99,
        name: "Ello Asty",
        years: 22,
    }
];
const totalYears = pilots.reduce(function (accumulator, pilot) {
    
    //const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0);
    return accumulator + pilot.years;
}, 0);

const mostExpPilot = pilots.reduce(function (oldest, pilot) {
    
    
    return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {
    
    });

Summarize

Combined with the above description, only the addition, deletion, modification and sequence modification of the operation array will cause the value of the original array to be changed.
There are the following seven methods that will change the value of the original array itself

  • push()Add N elements at the end
  • pop()delete an element at the end
  • shift()delete the first element
  • unshift()Add N elements at the first place
  • splice()Delete or add N elements at the specified position
  • sort()sort the array
  • reverse()reverse operation

The rest of the methods are operations such as obtaining a new array based on the original array. Generally, operations such as searching, intercepting a certain content, traversing, filtering, deduplication, and accumulation are commonly used. Specifically, there are the following 12 methods

  • slice()Intercept the specified range of elements
  • concat()Merge N arrays
  • join()Get the specified delimiter string, the default ,split
  • forEach()Traversing the array is generally used when doing comparisons or when each element has different processing logic
  • map()Traverse the array, modify the corresponding element value, and return a new array
  • filter()Filter specified condition elements
  • every()Determine whether the elements in the array meet the specified conditions
  • some()Determine whether the elements in the array have the value of the specified condition
  • find()Finds the value of the first element that meets the specified criteria
  • flat()Array flattening, which can be flattened according to the depth of input parameters
  • new Set()Combining class arrays, deduplication
  • reduce()It can return the data processed by the specified logic, such as returning the accumulation or finding the value of the specified condition

Guess you like

Origin blog.csdn.net/weiCong_Ling/article/details/131106903