Common operations of JavaScript array


Array is one of the common data types in JavaScript. I'll make a brief record and summary about its operation methods here.

This paper mainly includes:

  • Create array
  • Determine whether it is an array
  • Class array and array conversion
  • Array de duplication

You can choose to eat according to your own needs.

Create array

Creating an array is a basic skill. Its methods mainly include the following:

const arr = [1,2,3]                   // array literal 
const arr = [,,,]                     // Three element hole array
const arr = new Array(4)              // [,,,,]
const arr = new Array(4,2)            // [4,2]
const arr = Array.of(1,2,3)           // [1,2,3]

Among them, the most commonly used is array literal method.

Determine whether it is an array

The main methods to judge whether it is an array include:

// Method 1
[1,2,3] instanceof Array   
// Method 2
[1,2,3].constructor === Array
// Method 3[1,2,3]) === '[object Array]'
// Method 4
// Method 5 (compatible writing)
function isArray(arr){
    return Array.isArray ? 
        Array.isArray(arr) === '[object Array]'

Generally, the most commonly used method should be isArray.

Class array and array conversion

The data structure we sometimes encounter is not a pure array, which is generally classified as "class array". Class array can be transformed into a pure array with the following methods:

const x = document.querySelectorAll('a');
// Method 1;
// Method 2
// Method 3
// Method 4
function toArray(x){
    let res = []
    for(item of x){
    return res
// Method 5
// Method 6

Methods 5 and 6 essentially take advantage of the characteristics of apply, that is, the second parameter (array or class array) passed to apply will be converted into a parameter list, and these parameters will be sent to the called method (new Array or concat).

Array de duplication

Array de duplication essentially requires comparing whether two elements are equal. If they are equal, one element will be discarded. For accurate judgment, object is used here Is for comparison.

1) Using set to remove duplication

Set requires no repetition of elements, so you can remove the duplication after converting the array to set, and then convert it back to the array.

function unique(arr){
    return Array.from(new Set(arr))
    // return [ Set(arr)]

2) Double cycle + splice

The outer loop traverses all elements, and the inner loop traverses all elements after the current element. If they are found to be equal, use splice to remove one. Remember to back off one grid at a time in the inner loop, otherwise some elements will be missed

function unique(arr){
    for(let i = 0;i < arr.length;i++){
        for(let j = i + 1;i < arr.length;j++){
    return arr

3) New array + includes

Create a new array. Before adding an element to the array, check whether the element already exists in the array:

function unique(arr){
    const res = []
    arr.forEach((item,index) => {
        // You can also if(res.indexOf(item) == -1), but NaN cannot be judged correctly

4)reduce + includes

function unique(arr){
    return arr.reduce((acc,cur) => {
        // return acc.includes(cur) ? acc : acc.concat(cur)
        return acc.includes(cur) ? acc : [...acc,cur]

5) New array + sort

According to the mechanism of sort (call toStrng on each element, and then sort at the string level), the equal elements are gathered together. Create a new array. Before adding an element to the array, check whether the element is equal to the previous element. If yes, it belongs to a duplicate element:

function unique(arr){
    const res = [arr[0]]
    for(let i = 1;i < arr.length;i++){
    return res

6) New array + using object attributes

This method is actually the same as "new array + includes". Create a new array. Before adding an element to the array, check whether the element has been used as an attribute of the object:

// The object attribute value can be considered as the number of times the element is repeated
function unique(arr){
    const res = []
    const obj = {}
    arr.forEach((item,index) => {
            obj[item] = 1
        } else {
    return res

What is detected here is the attribute name of the object, and the attribute name is essentially a string. Therefore, it will be considered that obj[true] and obj["true"] are equal, resulting in the element true or the element "true" not being put into the new array

7) Using map

It is essentially the same as the above method, but there is no need to create a new array:

function unique(arr){
    let map = new Map()
    for(item of arr){
    return []

8)filter + indexOf

Get rid of duplicate elements. From another perspective, keep those elements whose index is equal to the index of the first occurrence. Such elements can be filtered out by filter and put into an array:

function unique(arr){
    return arr.filter((item,index) => index === arr.indexOf(item))

The disadvantage of using indexOf is that NaN cannot be judged correctly.


The above is a summary of some basic operation methods related to arrays.

~ End of this article, thank you for reading!


Learn interesting knowledge, make interesting friends and shape interesting souls!

Hello, I'm Programming samadhi Hermit Wang, my official account is " Programming samadhi "Welcome to pay attention and hope you can give us more advice!

Keywords: Javascript Front-end array

Added by TomatoLover on Sat, 05 Feb 2022 19:56:35 +0200