17 JavaScript One-Liners

17 JavaScript One-Liners

1. DOM & BOM related

1. Check if the element has focus

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


2. Get all sibling nodes of an element

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

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


3. Get the selected text

const getSelectedText = () => window.getSelection().toString();


4. Return to the previous page

history.back();
// or history.go(-1);


5. Clear all cookies

const clearCookies = () => document.cookie
  .split(';')
  .forEach((c) =>(document.cookie = c.replace(/^ +/, '')
  .replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));


6. Convert cookies to objects

const cookies = document.cookie
.split(';')
.map((item) => item.split('='))
.reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});

2. Array related

7. Comparing two arrays

// `a` and `b` are an array const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// or const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);

// Example isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false


8. Convert an array of objects to an object

const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
// or const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));

// Example toObject([
  { id: '1', name: 'Alpha', gender: 'Male' },
  { id: '2', name: 'Bravo', gender: 'Male' },
  { id: '3', name: 'Charlie', gender: 'Female' }],
'id');

/*
{
'1': { id: '1', name: 'Alpha', gender: 'Male' },
'2': { id: '2', name: 'Bravo', gender: 'Male' },
'3': { id: '3', name: 'Charlie', gender: 'Female' }
}
*/

9. Counting by properties of an array of objects

const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});

// Example countBy([
{ 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': 2, 'ford': 2, 'bmw': 1 }

10. Check if the array is empty

const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;

// Example isNotEmpty([]); // false
isNotEmpty([1, 2, 3]); // true

3. Object Related

11. Check if multiple objects are equal

const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));

// Example isEqual({ foo: 'bar' }, { foo: 'bar' }); // true
isEqual({ foo: 'bar' }, { bar: 'foo' }); // false


12. Extracting attribute values ​​from an array of objects

const pluck = (objs, property) => objs.map((obj) => obj[property]);

// Example pluck([
  { name: 'John', age: 20 },
  { name: 'Smith', age: 25 },
  { name: 'Peter', age: 30 },
],
'name');

// ['John', 'Smith', 'Peter']

13. Reverse the keys and values ​​of an object

const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});
// or const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));

// Example invert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' }

14. Remove all empty and undefined properties from objects

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));

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

15. Sort objects by properties

const sort = (obj) =>
  Object.keys(obj)
    .sort()
    .reduce((p, c) => ((p[c] = obj[c]), p), {});

// Example const colors = {
  white: '#ffffff',
  black: '#000000',
  red: '#ff0000',
  green: '#008000',
  blue: '#0000ff',
};
sort(colors);
/*
{
  black: '#000000',
  blue: '#0000ff',
  green: '#008000',
  red: '#ff0000',
  white: '#ffffff',
}
*/

16. Check if an object is a Promise

const isPromise = (obj) =>
  !!obj &&
  (typeof obj === 'object' || typeof obj === 'function') &&
  typeof obj.then === 'function';


17. Check if the object is an array

const isArray = (obj) => Array.isArray(obj);

This is the end of this article about JavaScript one-line programs. For more relevant JavaScript one-line program content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 18 killer JavaScript one-liners
  • 25 JavaScript one-line codes commonly used in development (summary)
  • Single line JS implements the input rules of mobile money format

<<:  Solution to the problem that input in form cannot be submitted when disabled

>>:  A brief discussion on the difference between readonly and disable attributes of input in HTML

Recommend

A summary of some of the places where I spent time on TypeScript

Record some of the places where you spent time on...

Detailed explanation of how to upgrade software package versions under Linux

In the Linux environment, you want to check wheth...

js to achieve a simple magnifying glass effect

This article shares the specific code of js to ac...

Linux system command notes

This article describes the linux system commands....

Detailed explanation of Apache website service configuration based on Linux

As an open source software, Apache is one of the ...

When backing up files in Centos7, add the backup date to the backup file

Linux uses files as the basis to manage the devic...

Docker Gitlab+Jenkins+Harbor builds a persistent platform operation

CI/CD Overview CI workflow design Git code versio...

12 Javascript table controls (DataGrid) are sorted out

When the DataSource property of a DataGrid control...

Specific method to delete mysql service

MySQL prompts the following error I went to "...

Network configuration of Host Only+NAT mode under VirtualBox

The network configuration of Host Only+NAT mode u...

How to implement remote automatic backup of MongoDB in Linux

Preface After reading the previous article about ...

Nginx uses reverse proxy to implement load balancing process analysis

Introduction Based on docker container and docker...