Home > Web Front-end > JS Tutorial > body text

Introduction to common array operations in JavaScript (code examples)

不言
Release: 2019-04-04 11:00:11
forward
1635 people have browsed it

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)
Copy after login

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

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

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]
Copy after login

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]
Copy after login

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]
Copy after login

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));
Copy after login

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] 降序
Copy after login

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]
Copy after login

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
Copy after login
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)
Copy after login

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]);
Copy after login

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);
Copy after login

Replacement plan:

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

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
Copy after login

Replacement Solution:

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

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);
Copy after login

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;
}
Copy after login

Loop fill -- ES6

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

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

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

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

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

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 });
Copy after login

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}
Copy after login

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 }
Copy after login

[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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!