30+ Most Frequently Used JavaScript Code Snippets for Common Tasks | JavaScript Examples

By | August 8, 2021
 

Array

Array deduplication

function noRepeat(arr) {
  return [...new Set(arr)];
}

Find the largest array

function arrayMax(arr) {
  return Math.max(...arr);
}

Find the smallest array

function arrayMin(arr) {
  return Math.min(...arr);
}

Returns the original array divided by an array whose size is the length

function chunk(arr, size = 1) {
  return Array.from(
    {
      length: Math.ceil(arr.length / size),
    },
    (v, i) => arr.slice(i * size, i * size + size)
  );
}

Check the number of occurrences of an element in the array

function countOccurrences(arr, value) {
  return arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
}

Flatten array

  • Default depth expand all
function flatten(arr, depth = -1) {
  if (depth === -1) {
    return [].concat(
      ...arr.map((v) => (Array.isArray(v) ? this.flatten(v) : v))
    );
  }
  if (depth === 1) {
    return arr.reduce((a, v) => a.concat(v), []);
  }
  return arr.reduce(
    (a, v) => a.concat(Array.isArray(v) ? this.flatten(v, depth - 1) : v),
    []
  );
}

Compare two arrays and return the different elements

function diffrence(arrA, arrB) {
  return arrA.filter((v) => !arrB.includes(v));
}

Return the same elements in two arrays

function intersection(arr1, arr2) {
  return arr2.filter((v) => arr1.includes(v));
}

Delete n elements from the right

function dropRight(arr, n = 0) {
  return n < arr.length ? arr.slice(0, arr.length - n) : [];
}

Intercept the first eligible element and subsequent elements

function dropElements(arr, fn) {
  while (arr.length && !fn(arr[0])) arr = arr.slice(1);
  return arr;
}

Returns the elements of the subscript interval nth in the array

function everyNth(arr, nth) {
  return arr.filter((v, i) => i % nth === nth - 1);
}

Returns the nth element in the array

  • Support negative numbers
function nthElement(arr, n = 0) {
  return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
}

Returns the head element of the array

function head(arr) {
  return arr[0];
}

Return the last element of the array

function last(arr) {
  return arr[arr.length - 1];
}

Array shuffle

function shuffle(arr) {
  let array = arr;
  let index = array.length;

  while (index) {
    index -= 1;
    let randomInedx = Math.floor(Math.random() * index);
    let middleware = array[index];
    array[index] = array[randomInedx];
    array[randomInedx] = middleware;
  }

  return array;
}

Browser Object BOM

Determine whether the browser supports CSS properties

/** * Inform the browser of the specified CSS attributes supported by the browser*@param {String} key-The css attribute is the name of the attribute and does not need to be prefixed*@returns {String}-Supported attributes*/
function validateCssKey(key) {
  const jsKey = toCamelCase(key); // Some css attributes are formed by hyphens
  if (jsKey in document.documentElement.style) {
    return key;
  }
  let validKey = "";
  // The attribute name is in the form of prefix in js, and the attribute value is in the form of prefix in css
  // After trying, Webkit can also be a lowercase first letter webkit
  const prefixMap = {
    Webkit: "-webkit-",
    Moz: "-moz-",
    ms: "-ms-",
    O: "-o-",
  };
  for (const jsPrefix in prefixMap) {
    const styleKey = toCamelCase(`${jsPrefix}-${jsKey}`);
    if (styleKey in document.documentElement.style) {
      validKey = prefixMap[jsPrefix] + key;
      break;
    }
  }
  return validKey;
}

/** * Convert a hyphenated string into a camel case string */
function toCamelCase(value) {
  return value.replace(/-(\w)/g, (matched, letter) => {
    return letter.toUpperCase();
  });
}

/** * Check whether the browser supports a certain CSS attribute value (es6 version) *@param {String} key-The css attribute name to which the checked attribute value belongs*@param {String} value-CSS attribute value to be checked (without prefix) *@returns {String}-Returns the attribute value supported by the browser*/
function valiateCssValue(key, value) {
  const prefix = ["-o-", "-ms-", "-moz-", "-webkit-", ""];
  const prefixValue = prefix.map((item) => {
    return item + value;
  });
  const element = document.createElement("div");
  const eleStyle = element.style;
  // The case of applying each prefix, and the case without a prefix should be applied at the end, depending on what kind of situation the browser is effective at the end
  // This is the best last element in the prefix is ``
  prefixValue.forEach((item) => {
    eleStyle[key] = item;
  });
  return eleStyle[key];
}

/** * Check whether the browser supports a certain CSS attribute value*@param {String} key-The css attribute name to which the checked attribute value belongs*@param {String} value-CSS attribute value to be checked (without prefix) *@returns {String}-Returns the attribute value supported by the browser*/
function valiateCssValue(key, value) {
  var prefix = ["-o-", "-ms-", "-moz-", "-webkit-", ""];
  var prefixValue = [];
  for (var i = 0; i < prefix.length; i++) {
    prefixValue.push(prefix[i] + value);
  }
  var element = document.createElement("div");
  var eleStyle = element.style;
  for (var j = 0; j < prefixValue.length; j++) {
    eleStyle[key] = prefixValue[j];
  }
  return eleStyle[key];
}

function validCss(key, value) {
  const validCss = validateCssKey(key);
  if (validCss) {
    return validCss;
  }
  return valiateCssValue(key, value);
}

Return the current web page address

function currentURL() {
  return window.location.href;
}

Get the scroll bar position

function getScrollPosition(el = window) {
  return {
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
  };
}

Get the parameters in the url

function getURLParameters(url) {
  return url
    .match(/([^?=&]+)(=([^&]*))/g)
    .reduce(
      (a, v) => (
        (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
      ),
      {}
    );
}

Page jump, whether it is recorded in history

function redirect(url, asLink = true) {
  asLink ? (window.location.href = url) : window.location.replace(url);
}

Scroll bar back to top animation

function scrollToTop() {
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  } else {
    window.cancelAnimationFrame(scrollToTop);
  }
}

Copy text

function copy(str) {
  const el = document.createElement("textarea");
  el.value = str;
  el.setAttribute("readonly", "");
  el.style.position = "absolute";
  el.style.left = "-9999px";
  el.style.top = "-9999px";
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0
      ? document.getSelection().getRangeAt(0)
      : false;
  el.select();
  document.execCommand("copy");
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
}

Type of testing equipment

function detectDeviceType() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? "Mobile"
    : "Desktop";
}

Cookie

Increase

function setCookie(key, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie =
    key +
    "=" +
    escape(value) +
    (expiredays == null ? "" : ";expires=" + exdate.toGMTString());
}

Delete

function delCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null) {
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  }
}

Check

function getCookie(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) {
    return arr[2];
  } else {
    return null;
  }
}

Date

Timestamp converted to time

  • The default is the current time conversion result
  • isMs is whether the timestamp is in milliseconds
function timestampToTime(timestamp = Date.parse(new Date()), isMs = true) {
  const date = new Date(timestamp * (isMs ? 1 : 1000));
  return `${date.getFullYear()}-${
 date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
 }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}

Document Object DOM

Fixed scroll bar

/** * Function description: Some business scenarios, such as when a pop-up box appears, need to prohibit page scrolling. This is a solution compatible with Android and iOS to prohibit page scrolling*/

let scrollTop = 0;

function preventScroll() {
  // Store the current scroll position
  scrollTop = window.scrollY;

  // Fix the position of the scrollable area. After the height of the scrollable area is 0, it cannot be scrolled.
  document.body.style["overflow-y"] = "hidden";
  document.body.style.position = "fixed";
  document.body.style.width = "100%";
  document.body.style.top = -scrollTop + "px";
  // document.body.style['overscroll-behavior'] = 'none'
}

function recoverScroll() {
  document.body.style["overflow-y"] = "auto";
  document.body.style.position = "static";
  // document.querySelector('body').style['overscroll-behavior'] = 'none'

  window.scrollTo(0, scrollTop);
}

Determine whether the current position is at the bottom of the page

  • The return value is true/false
function bottomVisible() {
  return (
    document.documentElement.clientHeight + window.scrollY >=
    (document.documentElement.scrollHeight ||
      document.documentElement.clientHeight)
  );
}

Determine whether the element is within the visible range

  • partiallyVisible is whether it is fully visible
function elementIsVisibleInViewport(el, partiallyVisible = false) {
  const { top, left, bottom, right } = el.getBoundingClientRect();

  return partiallyVisible
    ? ((top > 0 && top < innerHeight) ||
        (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}

Get element css style

function getStyle(el, ruleName) {
  return getComputedStyle(el, null).getPropertyValue(ruleName);
}

Enter full screen

function launchFullscreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
}

launchFullscreen(document.documentElement);
launchFullscreen(document.getElementById("id")); //An element enters the full screen

Exit Full Screen

function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}

exitFullscreen();

Full screen event

document.addEventListener("fullscreenchange", function (e) {
  if (document.fullscreenElement) {
    console.log(&quot;Enter full screen&quot;);
  } else {
    console.log(&quot;Exit Full Screen&quot;);
  }
});

Number

Digital thousandths division

function commafy(num) {
  return num.toString().indexOf(".") !== -1
    ? num.toLocaleString()
    : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
}

Generate random numbers

function randomNum(min, max) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * min + 1, 10);
    case 2:
      return parseInt(Math.random() * (max - min + 1) + min, 10);
    default:
      return 0;
  }
}