Preface: After reading many articles, THERE was no systematic summary of Array’s commonly used apis, so I had a bold idea to summarize some Array’s commonly used apis and some knowledge points related to Array that are often asked in interviews.

Opening diagram

Part of the IMPLEMENTATION of the API

map

Returns a new array after performing an operation on each item in the array

Function map (array, callback) {const arr = [] const arr = (let index = 0; index < array.length; index++) { const element = array[index]; const result = callback(element, index, array) arr.push(result) } return arr }Copy the code

reduce

Returns the value of the first argument in the callback function after operating on each item in the array

Ps: Very powerful, all the API in the array can be implemented through it

function reduce (array,callback, initValue) {
  // Result is the initial value
  let total = initValue
  // Iterate over each element of the current array, calling callback to get a cumulative result
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    total = callback(total, element, index, array)
  }

  // Return the result
  return total
}  
Copy the code

filter

Returns a new array of elements that meet the criteria

function filter (array,callback) {
  const arr = []
  // Iterate over each element of the current array, calling callback to get a Boolean value, if true, to add the current element to the ARR
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    const result = callback(element, index, array)
    if (result) {
      arr.push(element)
    }
  }
  return arr
}  
Copy the code

find

Returns the first element in an array that meets a condition

function find (array,callback) {
  // Iterate over each element of the current array, calling callback to get a Boolean value, or if true, return the current element
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    const result = callback(element, index)
    if (result) {
      return element
    }
  }
  return undefined
}  
Copy the code

findIndex

Returns the index of the first element in an array

function findIndex (array,callback) {
  // Iterate over each element of the current array, calling callback to get a Boolean value, if true, return the current element's index
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    const result = callback(element, index, array)
    if (result) {
      return index
    }
  }
  return -1
}
Copy the code

every

Function: Checks whether all elements in an array meet the criteria

function every (array,callback) {
  // Iterate over each element of the current array, call callback to get a Boolean value, if false, return false
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    const result = callback(element, index, array)
    if(! result) {return false}}return true
}  
Copy the code

some

Checks whether at least one element in an array meets the condition

function some (array,callback) {
  // Iterate over each element of the current array, call callback to get a Boolean value, and return true if true
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    const result = callback(element, index)
    if (result) {
      return true}}return false
}  
Copy the code

forEach

Function: Iterate over the number group

function forEach(array, callback) {
  // Iterate over each element of the current array, calling callback
  for (let index = 0; index < array.length; index++) { callback(array[index], index, array); }}Copy the code

concat

Joins an array

function concat (array, ... values) {
  const arr = [...array]
  // Iterate over values to add value or elements in value to arR
  values.forEach(value= > {
    if (Array.isArray(value)) { arr.push(... value) }else {
      arr.push(value)
    }
  })
  
  return arr
}
Copy the code

slice

Action: Cut an array

Ps: Array. Prototype. Slice. The call () and Array form () function, is a shallow copy an Array

function slice(array, begin, end) {
  const arr = []

  // If the array is empty, return it
  if (array.length===0) {
    return arr
  }
  // Processing is not specified
  begin = begin || 0
  end = end || array.length
  // Scope limits
  if (begin<0) {
    begin = 0
  }
  if (end>array.length) {
    end = array.length
  }

  // Implement the main operation first
  for (let index = begin; index < end; index++) {
    arr.push(array[index])
  }

  return arr
}
Copy the code

Array to heavy

First: use forEach+indexOf

function unique1(array){
    let arr = [];
    array.forEach(item= >{
        if(array.indexOf(item)===-1){
            arr.push(item)
        }
    })
    return arr;
}
Copy the code

Second: use forEach+ object containers

 function unique2(array){
     let arr = [];
     let tempObj = {};
     array.forEach(item= >{
         if(! tempObj.hasOwnProperty(item)){ tempObj[item] =true;
             arr.push(item)
         }
     })
     return array
 }
Copy the code

Set+… The operator

function unique3(array){
    return [...new Set(array)]
}
Copy the code

Find the most common element in an array

Create an object, insert the number of occurrences as a value into the object, obtain the value of the object, use math.max () to find the maximum value, and then backcheck the key based on the maximum value

 function findElement(array){
       let tempObj = {};
       array.forEach(item= >{ tempObj[item] = tempObj[item]? ++tempObj[item]:1;
       })
       let maxNumber = Math.max(... Object.values(tempObj));let maxValueArray = [];
       Object.keys(tempObj).forEach(item= >{
           if(tempObj[item]===maxNumber){
               maxValueArray.push(Number(item))
           }
       })
       return maxValueArray;
 }
Copy the code

Implement a stack structure with an array

After the advanced

function Stack() {

  // An array to hold element data
  let arr = []
  
  / / push into stack
  this.push = function (element) {
    arr.push(element)
  }

  // Pop ()
  this.pop = function () {
    // return arr.splice(arr.length-1, 1)
    return arr.pop()
  }

  // Check the stack top: peek()
  this.peek = function () {
    return arr[arr.length - 1]}// Stack number of elements: size()
  this.size = function () {
    return arr.length
  }
  // Is the stack empty: isEmpty()
  this.isEmpty = function () {
    return arr.length===0
  }

  / / the stack
  this.clear = function () {
    arr = []
  }
}

Copy the code

Implement a queue with an array

First in first out

function Queue() {

  // An array to hold element data
  const arr = []

  
  // Enqueue ()
  this.enqueue = function (element) {
    arr.push(element)
  }

  // dequeue()
  this.dequeue = function () {
    return arr.shift()
  }

  // check the queue header: front()
  this.front = function () {
    return arr[0]}// Check the number of elements: size()
  this.size = function () {
    return arr.length
  }
  // check whether the queue isEmpty: isEmpty()
  this.isEmpty = function () {
    return arr.length===0}}Copy the code

Array flattening

Method 1: recursion +concat+reduce

function flatten1(array){
    return array.reduce((initArray,item) = >{
        if(!Array.isArray(item)){
            initArray.push(item)
        }
        else{
            initArray = flatten1(item)
        }
        returninitArray; }}, [])Copy the code

Method 2 some + concat

function flatten2(array){
   letarr = [].concat(... array)while(arr.some(item= >Array.isArray(arr))){ arr = [].concat(... arr) }return arr;
}
Copy the code

Methods three toString + JSON parse

function flatten3(array){
    return JSON.parse(array.toString()).map(item= >Number(item))
}
Copy the code

conclusion

1 the static methods of Array form,of,isArray convert the pseudo-array to an Array, combine multiple elements into an Array, and check whether the Array type isArray

Instance methods of the 2 array include the (splice, Reverse, push, shift, unshift, pop, sort) and does not affect the original array (forEach, some, every, map, reduce, the find, slice, findIndex, indexOf, concat, find, filt waste er,join)

3. Data deduplication, array flattening, find out the elements that appear most frequently in array, stack, queue,