1. Several ways to determine whether it is an array

  • instanceof

The instanceof operator checks whether the constructor’s prototype property appears anywhere in the object’s prototype chain, returning a Boolean value

let arr = []
console.log(arr instanceof Array); // true
Copy the code
  • constructor

The constructor property of the instance points to the constructor, which can be used to determine whether it is an array

let arr = []
console.log(arr.constructor === Array);//true
Copy the code
  • Object.prototype.toString

Object. The prototype. ToString. Call () access to different types of objects

let arr = []
console.log(Object.prototype.toString.call(arr));//[object Array]
Copy the code
  • Array.isArray()

Array.isarray () is used to determine whether the value passed is an Array and returns a Boolean value

let arr = []
console.log(Array.isArray(arr));//true
Copy the code

Constructor and Prototype may be overwritten, so instanceof and constructor judgments may not be accurate

2. Array splitting

const listChunk = (list = [], chunkSize = 1) = > {
  const result = [];
  const tmp = [...list];
  if (!Array.isArray(list) || !Number.isInteger(chunkSize) || chunkSize <= 0) {
      return result;
  };
  while (tmp.length) {
      result.push(tmp.splice(0, chunkSize));
  };
  return result;
};

console.log(listChunk(['a'.'b'.'c'.'d']));// [['a'], ['b'], ['c'], ['d']]

console.log(listChunk(['a'.'b'.'c'.'d'.'e'].2));// [['a', 'b'], ['c', 'd'], ['e']]

console.log(listChunk(['a'.'b'.'c'.'d'].0));/ / []

console.log(listChunk(['a'.'b'.'c'.'d'] -1));/ / []
Copy the code

3. Array deduplication

  • Use ES6’s Set
/** Set does not allow duplicate elements */
let arr1 = [1.2.3.1.3.4]
let arr2 = Array.from(new Set(arr1))
console.log(arr2); // [1, 2, 3, 4]
Copy the code
  • Use the ES6 Map
/** Create an empty Map data structure that iterates through the array to be de-duplicated, storing each element of the array as a key in the Map. Since the Map does not have the same key, the final result is */
let arr = [1.0.2.3.1.0.4]
function unique(arr) {
     let map = new Map(a);let arr1 = []
     for (let i = 0, len = arr.length; i < len; i++) {
          if (map.has(arr[i])) {      // Check whether the key exists
              map.set(arr[i], true);
          }
          else {
              map.set(arr[i], false); arr1.push(arr[i]); }}return arr1;
}
console.log(unique(arr)); // 1, 0, 8, 3, -9, 7
Copy the code
  • Reduce is used to remove weight
let arr = [1, 2, 3, 4, 3, 2, 4]
let myArray = arr.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)
  }
  return accumulator
}, [])

console.log(myArray) //[ 1, 2, 3, 4 ]
Copy the code
  • Reweight the original array
let arr = [1.2.0.3.1.3]
const removeDuplicates = (nums) = > {
  let len = nums.length - 1
  // Go through the array from back to front.
  for(let i = len; i>=0; i--) {
      if(nums.indexOf(nums[i]) ! = i) { nums[i] = nums[len--] } }// Delete duplicates
  nums.splice(len+1)
  return nums
}
/ / test
removeDuplicates(arr)
console.log(arr); //[1, 2, 0, 3]
Copy the code

4. Array flattening

let arr = [1.2[3.4], [5[6.7]], 8];
// The first method:
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5, 6, 7, 8]

// Second method:
console.log(arr.toString().split(', ')); // [1, 2, 3, 4, 5, 6, 7, 8]

// Third method:
function flatten(arr) {
    return arr.reduce((prev, item) = > {
        return prev.concat(Array.isArray(item) ? flatten(item) : item); }}, [])console.log(flatten(arr)); // [1, 2, 3, 4, 5, 6, 7, 8]
Copy the code

5. Array Curryization

function sum(){
  var arr = [].slice.apply(arguments);
  var fn = function(){
      arr = arr.concat([].slice.apply(arguments))
      return fn;
  }
  fn.sumOf = function(){
      return  arr.reduce((total,num) = >total+num,0);
  }
  return fn;
}
console.log(sum(1.3).sumOf()) / / 4
console.log(sum(1.2) (3.4).sumOf())/ / 10
Copy the code

6. The array is out of order

// The first method
function arrScrambling(arr) {
  for (let i = 0; i < arr.length; i++) {
    const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
    [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
  }
  return arr;
}
console.log(arrScrambling([1.2.3.4])) // [1, 4, 2, 3]

// The second method
const shuffleArray = (arr) = > arr.sort(() = > 0.5 - Math.random());
console.log(shuffleArray([1.2.3.4])); // [1, 2, 4, 3]
Copy the code

7. Count the number of occurrences of each element in the array

let charArray = ['a'.'b'.'c'.'a'.'c'];
let charObject = charArray.reduce(function (allchars, char) {
  if (char in allchars) {
    allchars[char]++;
  } else {
    allchars[char] = 1;
  }
  return allchars;
}, {});
console.log(charObject); // { a: 2, b: 1, c: 2 }
Copy the code

8. Implement the map method of array

// Loop implementation
const myMap = function(fn, context) {
    let arr = Array.prototype.slice.call(this)
    let mapArr = Array(a)// Avoid sparseness
    const temArr = Reflect.ownKeys(arr)
    / / delete the length
    temArr.pop()
    for (let i of temArr) {
        console.log('i', i);
       mapArr[i] = fn.call(context, arr[i], i, this)}return mapArr
    }
    Array.prototype.myMap = myMap
    console.log([1.2.3].myMap(number= > number + 1)) //[2, 3, 4]

// Implement using reduce
Array.prototype.reduceMap = function(fn, context) {
    let arr = Array.prototype.slice.call(this)
    return arr.reduce((pre, cur, index) = > {
        return [...pre, fn.call(context, cur, index, this})], [])}console.log([1.2.3].reduceMap(number= > number + 1)); //[2, 3, 4]
Copy the code

9. Implement the reduce method of arrays

Array.prototype.myReduce = function(fn, initValue) {
    let arr = Array.prototype.slice.call(this)
    let res, startIndex = 0
    // if (! initValue) {
    // // finds the first non-empty element and subscript
    // for (let index = 0; index < arr.length; index++) {
    // if(! arr.hasOwnProperty(index)) continue
    // res = arr[index];
    // startIndex = index
    // break
    / /}
    // } else {
    // res = initValue
    // }
    // for (let index = ++startIndex; index < arr.length; index++) {
    // if(! arr.hasOwnProperty(index)) continue
    // res = fn.call(null, res, arr[index], index, this)
    // }
    // return res

    // Avoid sparse arrays and delete length
    let tempArr
    (tempArr = Reflect.ownKeys(arr)).pop()
    if (initValue) {
        res = initValue
    } else {
        res = arr[tempArr[0]]
        tempArr.shift()
    }
    for (const i of tempArr) {
        res = fn.call(null, res, arr[i], i, this)}return res
}
console.log([2.4.6.8].myReduce((pre, cur) = > pre + cur, 1)); / / 21
Copy the code

10. Remove invalid values from arrays

Creates a new array containing all the non-false value elements in the original array. Examples of false, null,0, “”, undefined, and NaN are all considered “false values”.

const compact = arr= > arr.filter(Boolean)
console.log(compact([0.1.false.true.2.' '.3]));//[ 1, true, 2, 3 ]
Copy the code

11. Maximum value in the array

const max = arr= > Math.max(... arr.filter(v= > Boolean(v) || v === 0))
Copy the code

12. Object array deduplication

const uniqueBy = (arr, key) = > {
    return arr.reduce((acc, cur) = > {
        const ids = acc.map(item= > item[key])
        return ids.includes(cur[key]) ? acc : [...acc, cur]
    }, [])
}
const responseList = [
    { id: 1.a: 1 },
    { id: 2.a: 2 },
    { id: 3.a: 3 },
    { id: 1.a: 4 },
    { id: 2.a: 2 },
    { id: 3.a: 3 },
    { id: 1.a: 4 },
    { id: 2.a: 2}]console.log(uniqueBy(responseList, 'id'));
//[ { id: 1, a: 1 }, { id: 2, a: 2 }, { id: 3, a: 3 } ]
Copy the code