JavaScript

We’ve collected the most popular actions in JavaScript, ranging from creating promises, popular lodash functions in native JavaScript, DOM manipulation, and more.

Add to Pieces

With the following snippets, we collected some popular actions performed in JavaScript ranging from creating promises, popular lodash functions in native JavaScript, DOM manipulation, etc.

Create a promise

Tags: javascript,  promise

Create a Promise to handle asynchronous events.

new Promise((resolve, reject) => {
  // asynchronous operation

  // then in case of success
  resolve();
  // or
  reject("failure reason");
});

Related links:

  1. https://www.digitalocean.com/community/tutorials/understanding-javascript-promises
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://www.w3schools.com/js/js_promise.asp

Count occurrences

Tags: javascript,  count

Count the occurences of a value in an array.

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

Related links:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
  2. https://www.w3schools.com/jsref/jsref_reduce.asp

Defer

Tags: javascript,  defer

Delays execution of function until the current call stack is cleared.

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);

defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'

Related links:

  1. https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
  2. https://www.w3schools.com/jsref/met_win_settimeout.asp

Difference

Tags: javascript,  difference

Finds the difference between two arrays.

const difference = (a, b) => {
  const s = new Set(b);
  return a.filter(x => !s.has(x));
};

difference([1, 2, 3], [1, 2, 4]); // [3]

Related links:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has

Removes Duplicates from an Array

Tags: javascript,  array, set, duplicate

Remove duplicates from an array using a Set.

const unique = [...new Set(array)];

Related links:

  1. https://www.javascripttutorial.net/array/javascript-remove-duplicates-from-array/
  2. https://www.programiz.com/javascript/examples/remove-duplicate
  3. https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array

Find key

Tags: javascript,  object, key

Returns the first key that satisfies a given function.

const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));

Related links:

  1. https://bobbyhadz.com/blog/javascript-get-object-key-by-value
  2. https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-236.php

Flatten

Tags: javascript,  array, flatten

Flattens a deeply nested array up until the specified depth.

const flatten = arr => arr.flat(Infinity);

Related links:

  1. https://codeburst.io/how-to-flatten-a-nested-javascript-array-628e01b85512
  2. https://flexiple.com/flatten-array-javascript/

Intersection

Tags: javascript,  array, common elements

Gets an array with elements that are included in two other arrays.

const intersection = (a, b) => {
  const s = new Set(b);

  return a.filter(x => s.has(x));
};

Related links:

  1. https://www.techiedelight.com/find-intersection-arrays-javascript/
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has

Get URL path

Tags: javascript,  url

Gets the url path for a webpage using javascript.

const newURL = `${window.location.protocol}//${window.location.host}/${window.location.pathname}${window.location.search}`

Related links:

  1. https://stackoverflow.com/questions/6944744/javascript-get-portion-of-url-path
  2. https://www.w3schools.com/js/js_window_location.asp

Remove HTML tags

Tags: javascript,  html

Remove html tags from strings

const strippedString = originalString.replace(/(<([^>]+)>)/gi, "");

Related links:

  1. https://stackoverflow.com/questions/5002111/how-to-strip-html-tags-from-string-in-javascript
  2. https://stackoverflow.com/questions/822452/strip-html-from-text-javascript
  3. https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

Array to HTML list

Tags: javascript,  html

Converts the given array elements into <li> tags and appends them to the list of the given id.

const arrayToHTMLList = (arr, listID) =>
  document.querySelector(`#${listID}`).innerHTML += arr
    .map(item => `
  • ${item}
  • `) .join('');

    Related links:

    1. https://stackoverflow.com/questions/58572752/how-to-display-this-js-array-in-a-html-list
    2. https://www.30secondsofcode.org/js/s/array-to-html-list

    Has class

    Tags: javascript,  class, element

    Checks whether an element has a particular class.

    const hasClass = (el, className) => el.classList.contains(className);

    Related links:

    1. https://www.javascripttutorial.net/dom/css/check-if-an-element-contains-a-class/
    2. https://stackoverflow.com/questions/5898656/check-if-an-element-contains-a-class-in-javascript

    Get current time

    Tags: javascript,  date, time

    Get current date and time.

    const date = new Date()
    const currentTime = 
       `${date.getHours()}:${date.getMintues()}:${date.getSeconds()}`

    Related links:

    1. https://tecadmin.net/get-current-date-time-javascript/
    2. https://linuxhint.com/how_to_get_current_date_and_time_in_javascript/
    3. https://stackoverflow.com/questions/10599148/how-do-i-get-the-current-time-only-in-javascript

    Check valid JSON

    Tags: javascript,  json

    Checks whether a string is valid JSON.

    const isValidJSON = str => {
      try {
        JSON.parse(str);
      } catch (e) {
        return false;
      }
    
    	return true;
    };

    Related links:

    1. https://thewebdev.info/2021/06/12/how-to-check-if-a-string-is-json-in-javascript/
    2. https://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string

    Delay async

    Tags: javascript,  timeout, async

    Delays the execution of an asynchronous function by putting it into sleep.

    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

    Related links:

    1. https://www.sitepoint.com/delay-sleep-pause-wait/
    2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    Add multiple classes

    Tags: javascript,  class

    Adds multiple classes to the selected element.

    element.classList.add("active", "highlighted");

    Related links:

    1. https://bobbyhadz.com/blog/javascript-add-multiple-classes-to-element
    2. https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

    Aggregating results from multiple promises

    Tags: javascript,  promise

    Takes an array of promises as an input and gets resolved when all the promises get resolved or any of them gets rejected.

    Promise.all([ promise_1, promise_2 ]).then((values) => {
        // all input Promises resolved
    }).catch((reason) => {
        // one of input Promises rejected
    });

    Related links:

    1. https://www.freecodecamp.org/news/promise-all-in-javascript-with-example-6c8c5aea3e32/
    2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
    3. https://www.javascripttutorial.net/es6/javascript-promise-all/