Use Apply to add the array items to another array

const array = ['a'.'b'];
const elements = [0.1.2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
Copy the code

The function is executed only once

function once (fn){
  let called = false
  return function () {
    if(! called) { called =true
      fn.apply(this.arguments)}}}function func (){
    console.log(1);
}

/ / call
let onlyOnce = once(func);

/ / test
onlyOnce(); / / 1
onlyOnce(); / / does not perform
Copy the code

Image stabilization

/** * anti-shake *@param {Function} Func Specifies the callback function to execute@param {Number} Wait delay *@param {Boolean} Immediate Whether to execute * immediately@return null* /
let timeout;
function Debounce(func, wait = 3000, immediate = true) {
  // Clear the timer
  if(timeout ! = =null) clearTimeout(timeout);
  // Execute immediately
  if (immediate) {
    varcallNow = ! timeout; timeout =setTimeout(function() {
      timeout = null;
    }, wait);
    if (callNow) typeof func === 'function' && func();
  } else {
    // Set the timer so that the timeout will not be cleared after the last operation, so execute the func callback after the wait milliseconds
    timeout = setTimeout(function() {
      typeof func === 'function' && func();
    }, wait);
  }
}

Debounce(() = >console.log(1));
Copy the code

The recursive array is reduced to one dimension

let children = [1[2.3], [4[5.6[7.8]]], [9.10]].function simpleNormalizeChildren(children) {
            for (let i = 0; i < children.length; i++) {
                if (Array.isArray(children[i])) {
                    children = Array.prototype.concat.apply([], children);
                    simpleNormalizeChildren(children)
                }
            }
            return children;
        }

console.log(simpleNormalizeChildren(children)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code

Array dimension reduction (two-dimensional dimension reduction)

function simpleNormalizeChildren(children) {
            for (let i = 0; i < children.length; i++) {
                if (Array.isArray(children[i])) {
                    return Array.prototype.concat.apply([], children)
                }
            }
            return children
}
let arrs = [['1'], ['3']].const arr = simpleNormalizeChildren(arrs);
console.log(arr); / / / '1', '3'
Copy the code

Function calls are made using optional chains

function doSomething(onContent, onError) {
  try {
   // ... do something with the data
  }
  catch(err) { onError? .(err.message);// If onError is undefined, there will be no exception}}Copy the code

Checks for empty values in array objects

const data = [
  {
  	name:"maomin"
  },
  {
    name:""}]const arr = data.filter(item= >
    Object.values(item).includes(' '));console.log(arr.length>0?Null value:"No null value"); Free / / value
Copy the code

Count the number of occurrences of each element in the array

let names = ['Alice'.'Bob'.'Tiff'.'Bruce'.'Alice'];

let countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});

console.log(countedNames); // { Alice: 2, Bob: 1, Tiff: 1, Bruce: 1 }
Copy the code

Classify objects by attribute

let people = [
  { name: 'Alice'.age: 21 },
  { name: 'Max'.age: 20 },
  { name: 'Jane'.age: 20}];function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property];
    if(! acc[key]) { acc[key] = []; } acc[key].push(obj);return acc;
  }, {});
}

const groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);
/ / {
/ / 20:
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
/ /,
// 21: [{ name: 'Alice', age: 21 }]
// }
Copy the code

Converts a delimited string to an n-dimensional array

 const str = "A-2-12";
 const str1 = str.split(The '-');
 console.log(str1);
 const arr = str1.reverse().reduce((pre,cur,i) = > {
 if(i==0)
  { pre.push(cur)
   return pre
 }
  return [cur,pre]
},[])
 
console.log(arr) // ["A"["B",["C"]]]
Copy the code