Home  >  Article  >  Web Front-end  >  Introduction to common array operations in JavaScript (code examples)

Introduction to common array operations in JavaScript (code examples)

不言
不言forward
2019-04-04 11:00:111814browse

This article brings you an introduction to common array operations in JavaScript (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In daily development, the front-end processing of data is inseparable. Here we will sort out the new array api of ES6/ES7/ES8...

Flat n-dimensional array

Array.flat() -- ES10

The method will recursively traverse the array according to a specifiable depth and traverse all elements to The elements in the subarrays are combined into a new array and returned. Array.flat(n) is the API for flat arrays. n represents the dimension. When the n value is Infinity, the dimension is infinite.

[1,[2,3]].flat(2) //[1,2,3]
[1,[2,3,[4,5]].flat(3) //[1,2,3,4,5]
[1,[2,3,[4,5]]].toString()  //'1,2,3,4,5'
[1,[2,3,[4,5],[...]]].flat(Infinity)

The flat() method will remove empty items in the array:

var arr4 = [1, 2, , 4, 5];
arr4.flat(); // [1, 2, 4, 5]

Alternative solution: The essence is to use recursion and the array merging method concat to achieve flatness

function flatten(arr) {
    while(arr.some(item=>Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}
flatten([1,[2,3]]) //[1,2,3]
flatten([1,[2,3,[4,5]]) //[1,2,3,4,5]

The Array.from() method creates a new array instance from a similar array or iterable object.

From and set are used to deduplicate arrays; set is a new data type in ES6 that defines non-repeating arrays. Array.from converts a class array into an array.
Array.from(new Set([1,2,3,3,4,4])) //[1,2,3,4]
[...new Set([1,2,3,3,4,4])] //[1,2,3,4]

Alternative solution:

Array.prototype.distinct = function(){
    var arr = this,
        result = [],
        i,
        j,
        len = arr.length;
    for(i = 0; i < len; i++){
        for(j = i + 1; j < len; j++){
            if(arr[i] === arr[j]){ 
                j = ++i;
            }
        }
        result.push(arr[i]);
    }
    return result;
}
[1,2,3,3,4,4].distinct(); //[1,2,3,4]

Array de-coupling and merging

function combine(){ 
    let arr = [].concat.apply([], arguments);  //没有去重复的新数组 
    return Array.from(new Set(arr));
} 
var m = [1, 2, 2], n = [2,3,3]; 
console.log(combine(m,n));

Sort Array.sort()

[1,2,3,4].sort((a, b) => a - b); // [1, 2,3,4],默认是升序
[1,2,3,4].sort((a, b) => b - a); // [4,3,2,1] 降序

Alternative solution: ascending order

Array.prototype.bubleSort=function () {
    let arr=this,
        len = arr.length;
    for (let outer = len; outer >= 2; outer--) {
        for (let inner = 0; inner <= outer - 1; inner++) {
            if (arr[inner] > arr[inner + 1]) {
                //升序
                [arr[inner], arr[inner + 1]] = [arr[inner + 1], arr[inner]];
                //console.log([arr[inner], arr[inner + 1]]);
            }
        }
    }
    return arr;
}
[1,2,3,4].bubleSort(); //[1,2,3,4]

Find the maximum value in the array Math.max()

Return the maximum value in a given set of numbers. If at least one of the given arguments cannot be converted to a number, NaN is returned.

Math.max(...[1,2,3,4]) //4
Math.max.apply(this,[1,2,3,4]) //4
[1,2,3,4].reduce( (prev, cur,curIndex,arr)=> {
    return Math.max(prev,cur);
},0) //4
Math.max() is a built-in method of the Math object, and the parameter is a string;
reduce is the ES5 array api, and the parameters include functions and default initial values;
The function has four parameters , pre (last return value), cur (current value), curIndex (current value index), arr (current array)

Sum reduction

[1,2,3,4].reduce(function (prev, cur) {
    return prev + cur;
},0)

Replacement scheme: sum, Use slice to intercept and change the array, and then use recursive summation

function sum(arr) {
    var len = arr.length;
    if(len == 0){
        return 0;
    } else if (len == 1){
        return arr[0];
    } else {
        return arr[0] + sum(arr.slice(1));
    }
}
sum([1,2,3,4]);

Merge concat

The concat() method is used to merge two or more arrays. This method does not change the existing array, but returns a new array.
push() method adds one or more elements to the end of an array and returns the new length of the array.

[1,2,3,4].concat([5,6]) //[1,2,3,4,5,6]
[...[1,2,3,4],...[4,5]] //[1,2,3,4,5,6]
// 相当于 vegetables.push('celery', 'beetroot');
Array.prototype.push.apply( ['parsnip', 'potato'], ['celery', 'beetroot']);
console.log(vegetables);

Replacement plan:

let arr=[1,2,3,4];
[5,6].map(item=>{
    arr.push(item)
}) //arr值为[1,2,3,4,5,6]

Determine whether the value is included

includes(), find(), findIndex() are ES6 api

[1,2,3].includes(4)//false
[1,2,3].indexOf(4) //-1 如果存在换回索引
[1, 2, 3].find((item)=>item===3) //3 如果数组中无值返回undefined
[1, 2, 3].findIndex((item)=>item===3) //2 如果数组中无值返回-1

Replacement Solution:

[1,2,3].some(item=>{
    return item===3
}) //true 如果不包含返回false

Class array conversion Array.from() — ES6

Class array: has a length attribute, but the attribute is a non-negative integer. It doesn't have some methods of arrays, but that doesn't mean it can't use array methods.
For example: the value returned by document.getElementsByTagName('p') is an array class
call, apply: changes this in the slice to point to arguments, so arguments can also call the array method
Array.from is Create an array-like or iterable object as an array
The slice() method in the array object cuts the array without operating the original array, which can be called a shallow copy

var a={
    0:"aa",
    1:"cc",
    2:"dd",
    length:3
}
var callArr = Array.prototype.slice.call(a);
var applyArr = Array.prototype.slice.apply(a)
var fromArr = Array.from(a)
console.log(a,callArr, applyArr, fromArr);

Array.prototype.slice Understanding:

Array.prototype.slice = function(start,end){
    var result = new Array();
    start = start || 0;
    end = end || this.length; //this指向调用的对象,当用了call后,能够改变this的指向,也就是指向传进来的对象,这是关键
    for(var i = start; i < end; i++){
        result.push(this[i]);
    }
    return result;
}

Loop fill -- ES6

[1,2,3].fill(1)
[1,2,3].map(()=>0)

every -- ES5; whether each item satisfies the condition, a Boolean value is returned

    [1,2,3].every(item=>{return item>2})// false

some As long as one item is satisfied, Returns a Boolean value

    [1,2,3].some (item=>{return item>2})// true

Filter array filter -- ES5

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

[1,2,3].filter(item=>{return item >=2 });

Objects and arrays convert keys, values, entries,

fromEntries

Object.keys({name:'张三',age:14}) //['name','age']
Object.values({name:'张三',age:14}) //['张三',14]
Object.entries({name:'张三',age:14}) //[[name,'张三'],[age,14]]
Object.fromEntries([name,'张三'],[age,14]) //ES10的api,Chrome不支持 , firebox输出{name:'张三',age:14}

new Map() constructor accepts an iterable entry. With the help of the Object.entries method, you can easily convert Object to Map:

var obj = { foo: "bar", baz: 42 }; 
var map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

[Related recommendations: JavaScript Video Tutorial]

The above is the detailed content of Introduction to common array operations in JavaScript (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete