JavaScript One Liners

JavaScript is a powerful language that can be used to write complex applications, but it can also be used to write simple one-liners that can make your code more concise and easier to read. In this article, we will look at some of the most useful JavaScript one-liners that you can use to make your code more efficient and readable.

Source

Sourced from KhalidSaifullahFuad/JavaScript-One-Liners


ARRAY

Check if a variable is an Array

const isArray = Array.isArray(arr);
const isArray = arr instanceof Array;

Sum of an Array of Number

const sum = (arr) => arr.reduce((a, b) => a + b);

Average of an Array of Number

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;

Sort an Array

const sort = (arr) => arr.slice().sort((a, b) => a - b);

Clone an Array

const clone = (arr) => arr.slice();
const clone = (arr) => [...arr];

Find Unique Values in an Array

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

Get the Last Element from an Array

const lastElement = (arr) => arr[arr.length-1];
const lastElement = (arr) => arr.slice(-1)[0];
const lastElement = (arr) => arr.slice().pop();

Shuffle an Array

const shuffle = (arr) => arr.slice().sort(() => Math.random() - 0.5);

Remove Duplicates from an Array

const removeDuplicates = (arr) => [...new Set(arr)];

Merge two Arrays

const merge = (arr1, arr2) => [].concat(arr1, arr2);
const merge = (arr1, arr2) => [...arr1, ...arr2];

Merge and Remove the Duplications

const merge = (arr1, arr2) => [...new Set(arr1.concat(arr2))];
const merge = (arr1, arr2) => [...new Set([...arr1, ...arr2])];

Remove Falsy value from Array

const removeFalsyValues = (arr) => arr.filter(x => x);
const removeFalsyValues = (arr) => arr.filter(Boolean);


STRING

Capitalize a String

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);

String Reverse

const reverseString = (str) => str.split("").reverse().join("");
const reverseString = (str) => [...str].reverse().join();

Convert a String to a Number

const toNumber = (str) => Number(str);
const toNumber = (str) => +str;

Convert a String to a Character Array

const toCharArray = (str) => str.split('');
const toCharArray = (str) => [...str];
const toCharArray = (str) => Array.from(str);
const toCharArray = (str) => Object.assign([], str);

Convert Snake case to Camel case

const snakeToCamel = (str) => str.toLowerCase().replace(/(_\w)/g, (word) => word.toUpperCase().substr(1));


DATE

Days between two dates

const daysBetweenDates = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24));

Weekday of a Date

const getWeekday = (date) => ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][date.getDay()];
const getWeekday = (date) => date.toLocaleString('en-US', {weekday: 'long'});


RANDOM

Random Number Generator

const randomNumber = (rangeStart, rangeEnd) => new Date().getTime() % rangeEnd + rangeStart;
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

Random Hexadecimal Color Generator

const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;

Random Boolean Generator

const randomBoolean = () => Math.random() >= 0.5;


VALIDATION

Check if an Array Is Empty

const isEmpty = (arr) => !Array.isArray(arr) || !arr.length;

Check if Array includes a Value

const includes = (arr, value) => arr.indexOf(value) != -1;
const includes = (arr, value) => arr.includes(value);

Check if the date is Weekend

const isWeekend = (date) => [5, 6].indexOf(date.getDay()) !== -1;


REGULAR EXPRESSION

Phone Validation

const checkPhoneNumber = (phone) => (/^(\+91|0)?\s?\d{10}$/).test(phone);

CamelCase Validation

const isCamelCase = (str) => (/^[a-z][a-zA-Z0-9]$/).test(str);


MISCELLANEOUS

Get selected text

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

Toggle a Boolean

const toggle = (flag) => !flag;

Swap to Variables

const swap = (a,b) => [a,b] = [b,a];


Reference

© 2024 Marko Bajlovic. Version 5.0.9.