Some data processing methods that may be commonly used in JS

Some data processing methods that may be commonly used in JS

DOM processing

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

Check if an element is focused

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

Check if the user has scrolled to the bottom of the page

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

Get all sibling elements of an element

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

Get the position of an 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 an element after another element

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

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

P.S. Insert an 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);

P.S. Insert the given HTML before the element

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

Scroll to top of page (Back to top)

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

Arrays

Array empty check

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

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

Cloning an Array

// `arr` is an array
const clone = arr => arr.slice(0);

// Or
const clone = arr => [...arr];

// Or
const clone = arr => Array.from(arr);

// Or
const clone = arr => arr.map(x => x);

// Or
const clone = arr => JSON.parse(JSON.stringify(arr));

// Or
const clone = arr => arr.concat([]);

Find the index of the maximum value in an 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

Appendix: Index corresponding to the 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

Get the intersection of arrays

const getIntersection = (a, ...arr) => [...new Set(a)].filter(v => arr.every(b => b.includes(v)));

// Examples
getIntersection([1, 2, 3], [2, 3, 4, 5]); // [2, 3]
getIntersection([1, 2, 3], [2, 3, 4, 5], [1, 3, 5]); // [3]

Group a set of objects by key

const groupBy = (arr, key) => arr.reduce((acc, item) => ((acc[item[key]] = [...(acc[item[key]] || []), item]), acc), {});

// Example
groupBy([
    { branch: 'audi', model: 'q8', year: '2019' },
    { branch: 'audi', model: 'rs7', year: '2020' },
    { branch: 'ford', model: 'mustang', year: '2019' },
    { branch: 'ford', model: 'explorer', year: '2020' },
    { branch: 'bmw', model: 'x7', year: '2020' },
], 'branch');

/*
{
    audi: [
        { branch: 'audi', model: 'q8', year: '2019' },
        { branch: 'audi', model: 'rs7', year: '2020' }
    ],
    bmw:
        { branch: 'bmw', model: 'x7', year: '2020' }
    ],
    ford:
        { branch: 'ford', model: 'mustang', year: '2019' },
        { branch: 'ford', model: 'explorer', year: '2020' }
    ],
}
*/

Remove duplicate values ​​from an array

const removeDuplicate = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

// Example
removeDuplicate(['h', 'e', ​​'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); // ['h', 'e', ​​'w', 'r', 'd']

Sort the items in an array by the given key

const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k]) ? 1 : ((a[k] < b[k]) ? -1 : 0));

// Example
const people = [
    { name: 'Foo', age: 42 },
    { name: 'Bar', age: 24 },
    { name: 'Fuzz', age: 36 },
    { name: 'Baz', age: 32 },
];
sortBy(people, 'age');

// returns
// [
// { name: 'Bar', age: 24 },
// { name: 'Baz', age: 32 },
// { name: 'Fuzz', age: 36 },
// { name: 'Foo', age: 42 },
// ]

method

Convert URL parameters to an object

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 a parameter from a URL

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

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

Prefixing integers with zero

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'

Rounds a number to a 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 the 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 if a string is a palindrome

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

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

Convert a 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 a 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

Escaping 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 to whole 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

This concludes this article about some commonly used data processing methods in JS. For more information about commonly used JS data processing methods, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Super detailed basic JavaScript syntax rules
  • js basic syntax and maven project configuration tutorial case
  • Detailed explanation of destructuring assignment syntax in Javascript
  • js realizes the dynamic loading of data by waterfall flow bottoming out
  • js realizes two-way data binding (accessor monitoring)
  • Detailed explanation of basic syntax and data types of JavaScript

<<:  How to clear mysql registry

>>:  Specific method of viewing user authorization information in mysql

Recommend

Win10 configuration tomcat environment variables tutorial diagram

Before configuration, we need to do the following...

Sample code for CSS image animation effects (photo frame)

This article introduces the sample code of CSS pi...

How to install and use Ubuntu Docker

Table of contents 1. Automatic installation using...

Windows Server 2008 R2 Multi-User Remote Desktop Connection Licensing

At work, we often need remote servers and often e...

Example of how to implement keepalived+nginx high availability

1. Introduction to keepalived Keepalived was orig...

Vue.js implements tab switching and color change operation explanation

When implementing this function, the method I bor...

How to build DockerHub yourself

The Docker Hub we used earlier is provided by Doc...

Introduction to CSS BEM Naming Standard (Recommended)

1 What is BEM Naming Standard Bem is the abbrevia...

Design theory: people-oriented green design

Reflections on the two viewpoints of “people-orie...

A complete list of common Linux system commands for beginners

Learning Linux commands is the biggest obstacle f...

Detailed explanation of how to use Docker-Compose commands

You can manage and deploy Docker containers in a ...

MYSQL METADATA LOCK (MDL LOCK) theory and lock type test

Table of contents MYSQL METADATA LOCK (MDL LOCK) ...