SoFunction
Updated on 2025-03-10

Summary of common tools and functions of JavaScript array in one article

1. Implementation

if (!){
   = function(arg){
    return (arg) === '[object Array]';
  };
}

2. Convert class array to array

1. Borrow array method for conversion

// 1. slice
(arguments)
// 2. concat
[].([], arguments)

2. es6 mode conversion

// 1. ...Extended operator[...arguments]

// 2. ()
(arguments)

3. Determine whether it is an array

var a = [];
// 1. Based on instanceofa instanceof Array;
// 2. Based on constructor === Array;
// 3. Based on(a);
// 4. Based on getPrototypeOf(a) === ;
// 5. Based on(a) === '[object Array]';
// 6. By(a)

IV. Array method implementation

  = function(fn, context = window){
    let len = 
    for(let i = 0; i < len; i++){
        typeof fn === 'function' && (context, this[i], i)
    }
}

2. filter

 = function(fn, context = window){
    let len = ,
        result = []
    for(let i = 0; i < len; i++){
        if((context, this[i], i, this)){
            (this[i])
        }
    }
    return result
}

3. every

 = function(fn, context){
    let result = true,
        len = 
    for(let i = 0; i < len; i++){
        result = (context, this[i], i, this)
        if(!result){
            break
        }
    }
    return result
}

4. some

 = function(fn, context){
    let result = false,
        len = 
    for(let i = 0; i < len; i++){
        result = (context, this[i], i, this)
        if(result){
            break
        }
    }
    return result
}

5. findIndex

 = function (callback) {
    for (let i = 0; i < ; i++) {
        if (callback(this[i], i)) {
            return i
        }
    }
}

6. Reduce

 = function (fn, initialValue) {
    let arr = (this)
    let res, startIndex
    res = initialValue ? initialValue : arr[0]
    startIndex = initialValue ? 0 : 1
    for (let i = startIndex; i < ; i++) {
        res = (null, res, arr[i], i, this)
    }
    return res
}

5. Implement array flattening

let ary = [1, [2, [3, 4, 5]]]

1. Normal recursion + concat

const flatten = function(ary){
    let result = []

    for(let i = 0;i<;i++){
        if((ary[i])){
            result = (flatten(ary[i]))
        } else {
            (ary[i])
        }
    }
    return result
}

2. reduce+concat

const flatten = function(ary){
    return ((prev, next)=>{
        return ((next) ? flatten(next) : next)
    }, [])
}

3. while+concat

const flatten = function(ary){
    while((item=>(item))){
        ary = [].concat(...ary)
    }
    return ary
}

4. toString+split

const flatten = function(ary){
    return ().split(',')
}

5. flat

const flatten = function(ary){
    return (Infinity)
}

6. Regularity

const flatten6 = function(ary){
    let str = (ary)
    str = (/([|])/g, '')
    return (`[${str}]`)
}

6. Go to the heavy

1. Utilize ES6 syntax (extended operator)

const unique1 = (array) => {
  // return (new Set(array))
  return [...new Set(array)]
}

2. Use forEach()+ object container

const unique2 = (array) => {
  const arr = []
  const obj = {}
  (item => {
    if (!(item)) {
      obj[item] = true
      (item)
    }
  })
  return arr
}

3. Use forEach and indexOf

const unique3 = (array) => {
  const arr = []
  (item => {
    if ((item) === -1) {
      (item)
    }
  })
  return arr
}

4. Use filter+ indexOf

const unique4 = (array) => {
  return ((item,index) => {
    return (item) === index;
  })
}

5. Use forEach and include (essentially the same as 3)

const unique6 = (array) => {
  let result = [];
  (item => {
    if(!(item)){
      (item);
    }
  })
  return result;
 }

6. Use sort

const unique6 = (array) => {
  let result = (function (a,b) {
    return a - b;
  });
  for(let i = 0;i < ;i ++){
    if(result[i] === result[i+1]){
      (i + 1,1);
      i --;
    }
  }
  return result;
}

7. Double-layer for loop

function unique(array) {
    // res is used to store the results    var res = [];
    for (var i = 0, arrayLen = ; i &lt; arrayLen; i++) {
        for (var j = 0, resLen = ; j &lt; resLen; j++ ) {
            if (array[i] === res[j]) {
                break;
            }
        }
        // If array[i] is unique, then after executing the loop, j is equal to resLen        if (j === resLen) {
            (array[i])
        }
    }
    return res;
}
(unique(array)); // [1, "1"]

Sorting

1. Bubble sorting

principle:Use the previous item of the array to compare with the next item adjacent to the ones, determine the size/small, and exchange the position

const bubbleSort = function(ary){
    for(let i = 0; i <  - 1; i++){
        for(let j = 0; j <  - 1 - i; j++){
            if(ary[j] > ary[j+1]){
                [ary[j], ary[j+1]] = [ary[j+1], ary[j]]
            }
        }
    }
    return ary
}

2. Select Sort

principle:Use an item in the array to compare with all the following values ​​to determine the size/small, and exchange the position

const bubbleSort = function(ary){
    for(let i = 0; i <  - 1; i++){
        for(let j = i + 1; j < ; j++){
            if(ary[i] > ary[j]){
                [ary[i], ary[j]] = [ary[j], ary[i]]
            }
        }
    }
    return ary
}

3. Native sorting

((a, b)=>a-b)

4. Quick sort

principle:Take the middle value of the array as the benchmark, judge the large or small values ​​on the left and right sides, add them to the corresponding array, call them recursively, and then splice all the values ​​together.

const quick_sort = function(ary){
    if( < 1){
        return ary
    }
    let centerIndex = (/2)
    let centerVal = (centerIndex, 1)[0]
    let left = []
    let right = []
    (item => {
        item > centerVal ? (item) : (item)
    })
    return [...quick_sort(left), ...[centerVal], ...quick_sort(right)]
}

5. Insert sort

principle:First add the item in the array to the new array, compare each item in the loop array with the new array, and place the larger value in the lower value in the back and put it in front of the new array.

 const insertion_sort = function(ary){
    let newAry = (0, 1)
    for(let i = 0; i < ; i++){
        let cur = ary[i]
        for(let j =  - 1; j >= 0;){
            if(cur < newAry[j]){
                j--
                j === -1 && (cur)
            } else {
                (j + 1, 0, cur)
                j = -1
            }
        }
    }
    return [...newAry]
}

8. Maximum and Minimum Values

1. Assumption

const maxMin = function(ary){
    let [min, max] = [ary[0], ary[1]]
    (ele => {
        min > ele ? min = ele : null
        max < ele ? max = ele : null
    })
    return [min, max]
}

2. () + hypothesis

var arr = [6, 4, 1, 8, 2, 11, 23];
var result = arr[0];
for (var i = 1; i < ; i++) {
    result =  (result, arr[i]);
}
(result);

3. reduce

var arr = [6, 4, 1, 8, 2, 11, 23];
function max(prev, next) {
    return (prev, next);
}
((max));

4. Sort

var arr = [6, 4, 1, 8, 2, 11, 23];
(function(a,b){return a - b;});
(arr[ - 1])

5. Utilization

(null, ary)
// Extended operator(...arr)
// eval
var max = eval("(" + arr + ")");

Nine. Average

const balance = function(ary){
    ((a, b) => a - b)
    ()
    ()
    let num = 0
    (item => {
        num += item
    })
    return (num/).toFixed(2)
}

Ten. Array disordered

function shuffle(a) {
    var j, x, i;
    for (i = ; i; i--) {
        j = (() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
    return a;
}

11. Flatten the array and remove duplicate data from it, resulting in an ascending and non-repeat number

let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
(new Set((Infinity))).sort((a,b)=>{ return a-b})

This is the article about mastering common tools and functions in JavaScript arrays. For more related JS array tools, please search for my previous articles or continue browsing the following related articles. I hope you will support me in the future!