Some data processing methods that may be commonly used in JS

  • 2021-11-24 00:21:58
  • OfStack

Directory DOM processing array method Summarize

DOM processing

DOM provides a structured representation of a document and defines how to access the document structure through scripts. The purpose is actually a specification for js to operate html elements. DOM is composed of nodes.

Check whether 1 element is focused


const hasFocus = ele => (ele === document.activeElement);

Check whether the user scrolls to the bottom of the page


const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

Gets all siblings of 1 element


const siblings = ele => [].slice.call(ele.parentNode.children).filter((child) => (child !== ele));

Gets the position of the element relative to the document


const getPosition = ele => (r = ele.getBoundingClientRect(), { 
left: r.left + window.scrollX, top: r.top + window.scrollY
 });

// Example
getPosition(document.body);     // { left: 0, top: 0 }

Insert 1 element after another


const insertAfter = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);

// Or
const insertAfter = (ele, anotherEle) => anotherEle.insertAdjacentElement('afterend', ele);

Attachment: Insert 1 element before other elements


const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);

// Or
const insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);

Inserts the given HTML after the element


const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML('afterend', html);

Attachment: Insert the given HTML before the element


const insertHtmlBefore = (html, ele) => ele.insertAdjacentHTML('beforebegin', html);

Scroll to the top of the page (back to the top)


const goToTop = () => window.scrollTo(0, 0);

Array

Array empty judgment


// `arr` is an array
const isEmpty = arr => !Array.isArray(arr) || arr.length === 0;

// Examples
isEmpty([]);            // true
isEmpty([1, 2, 3]);     // false

Clone array


const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
0

Find the index corresponding to the maximum value in the array


const indexOfMax = arr => arr.reduce((prev, curr, i, a) => curr > a[prev] ? i : prev, 0);

// Examples
indexOfMax([1, 3, 9, 7, 5]);        // 2
indexOfMax([1, 3, 7, 7, 5]);        // 2

Attachment: Index corresponding to minimum value


const indexOfMin = arr => arr.reduce((prev, curr, i, a) => curr < a[prev] ? i : prev, 0);

// Examples
indexOfMin([6, 4, 8, 2, 10]);       // 3
indexOfMin([6, 4, 2, 2, 10]);       // 2

Gets the intersection of arrays


const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
3

Key to group 1 group of objects


const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
4

Delete duplicate values from an array


const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
5

Sorts the items in the array by the given key


const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
6

Method

Convert URL parameters to objects


const getUrlParams = query => Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v}), {});

// Examples
getUrlParams(location.search);              // Get the parameters of the current URL

getUrlParams('foo=Foo&bar=Bar');            // { foo: "Foo", bar: "Bar" }

// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar');   // { foo: ["Foo", "Fuzz"], bar: "Bar" }

Get the value of the parameter from URL


const getParam = (url, param) => new URLSearchParams(new URL(url).search).get(param);

// Example
getParam('http://domain.com?message=hello', 'message');     // 'hello'

Prefix an integer with zero


const isAtBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
9

Round the number 4 by 5 to the given number of digits


const prefixWithZeros = (number, length) => (number / Math.pow(10, length)).toFixed(length).substr(2);

// Or
const prefixWithZeros = (number, length) => `${Array(length).join('0')}${number}`.slice(-length);

// Or
const prefixWithZeros = (number, length) => String(number).padStart(length, '0');

// Example
prefixWithZeros(42, 5);     // '00042'

Truncates a number to a given number of decimal places without rounding


const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:\.\\d{0,${fixed}})?`))[0];

// Or
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);

// Examples
toFixed(25.198726354, 1);       // 25.1
toFixed(25.198726354, 2);       // 25.19
toFixed(25.198726354, 3);       // 25.198
toFixed(25.198726354, 4);       // 25.1987
toFixed(25.198726354, 5);       // 25.19872
toFixed(25.198726354, 6);       // 25.198726

Remove all null and undefined properties from the object


const removeNullUndefined = obj => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {});

// Or
const removeNullUndefined = obj => Object.entries(obj).filter(([_, v]) => v != null).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});

// Or
const removeNullUndefined = obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

// Example
removeNullUndefined({
    foo: null,
    bar: undefined,
    fuzz: 42,
});  

Check whether the string is palindrome


const isPalindrome = str => str === str.split('').reverse().join('');

// Examples
isPalindrome('abc');        // false
isPalindrom('abcba');       // true

Convert 1 string to camelCase


const toCamelCase = str => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');

// Examples
toCamelCase('background-color');            // backgroundColor
toCamelCase('-webkit-scrollbar-thumb');     // WebkitScrollbarThumb
toCamelCase('_hello_world');                // HelloWorld
toCamelCase('hello_world');                 // helloWorld

Convert String to PascalCase


const toPascalCase = str => (str.match(/[a-zA-Z0-9]+/g) || []).map(w => `${w.charAt(0).toUpperCase()}${w.slice(1)}`).join('');

// Examples
toPascalCase('hello world');    // 'HelloWorld'
toPascalCase('hello.world');    // 'HelloWorld'
toPascalCase('foo_bar-baz');    // FooBarBaz

Escape HTML special characters


const escape = str => str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');

// Or
const escape = str => str.replace(/[&<>"']/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[m]);

Replace multiple spaces with a single space


// Replace spaces, tabs and new line characters
const replaceSpaces = str => str.replace(/\s\s+/g, ' ');

// Only replace spaces
const replaceOnlySpaces = str => str.replace(/  +/g, ' ');

// Example
replaceSpaces('this\n   is     \ta    \rmessage');  // 'this is a message'

Sort the lines of a text document in alphabetical order


const sortLines = str => str.split(/\r?\n/).sort().join('\n');

// Reverse the order
const reverseSortedLines = str => str.split(/\r?\n/).sort().reverse().join('\n');

// Example
sortLines(`Thaddeus Mullen
Kareem Marshall
Ferdinand Valentine
Hasad Lindsay
Mufutau Berg
Knox Tyson
Kasimir Fletcher
Colton Sharp
Adrian Rosales
Theodore Rogers`);

/* Output */
/*
Adrian Rosales
Colton Sharp
Ferdinand Valentine
Hasad Lindsay
Kareem Marshall
Kasimir Fletcher
Knox Tyson
Mufutau Berg
Thaddeus Mullen
Theodore Rogers
*/

Truncate a string into complete words (beyond hiding)


const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;

// Example
truncate('This is a long message', 20, '...');  // 'This is a long...'

Unescape HTML special characters


const unescape = str => str.replace(/&amp;/g , '&').replace(/&lt;/g  , '<').replace(/&gt;/g  , '>').replace(/�*39;/g , "'").replace(/&quot;/g, '"');

Summarize


Related articles: