Ditching Dependencies: You don't need libraries for these JavaScript tasks
Adem Kouki
Posted on February 8, 2023
In this post, we will look at some of the most common tasks that developers do and see how we can do them without using any libraries or frameworks.
Clone an object
const obj = { a: 1, b: 2 };
const clone = obj.structuralClone();
Get the current URL
const url = new URL(window.location.href);
Remove multiple line breaks
const text = `Hello
World`;
const cleanText = text.replace(/\n{2,}/g, "\n");
Remove array duplicates
const arr = [1, 2, 3, 3, 4, 5, 5, 6];
const uniqueArr = [...new Set(arr)];
Generate a random number between two numbers
const min = 1;
const max = 10;
const random = Math.floor(Math.random() * (max - min + 1)) + min;
Shuffle an array
const arr = [1, 2, 3, 4, 5];
const shuffledArr = arr.sort(() => Math.random() - 0.5);
Detect Dark Mode
const isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
Generate a random color
const generateRandomHexColor = () =>
`#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
Sort an array of objects by a property
const arr = [
{ name: "Adem", age: 26 },
{ name: "Jane", age: 25 },
{ name: "Bob", age: 20 },
];
// Sort by age
const sortedArr = arr.sort((a, b) => a.age - b.age);
Get the intersection of arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const intersection = (a, ...arr) =>
[...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));
intersection(arr1, arr2); // [3, 4, 5]
Get the number of days in a month
const getDaysInMonth = (month, year) => new Date(year, month, 0).getDate();
daysInMonth(2, 2024);
// 29
Flatten an array
const flatten = (arr) =>
arr.reduce(
(a, b) => (Array.isArray(b) ? [...a, ...flatten(b)] : [...a, b]),
[]
);
flatten([
[1, 2],
[3, 4],
[5, 6],
]);
// [1, 2, 3, 4, 5, 6]
Check if two objects are equal
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
isEqual({ name: "Adem", age: 26 }, { name: "Adem", age: 26 });
// true
Slugify a string
const slugify = (str) =>
str
.toLowerCase()
.replace(/[^\w ]+/g, "")
.replace(/ +/g, "-");
slugify("Hello World");
// hello-world
If you enjoyed this article, please share it with your friends and colleagues. If you have any questions or suggestions, please leave a comment below.
💖 💪 🙅 🚩
Adem Kouki
Posted on February 8, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
tailwindcss Integrating Tailwind CSS with Other Frontend Frameworks for Admin Panels
November 30, 2024
webdev JavaScript Higher-Order Functions Made Easy: Learn with a Real-Life Example! 💡
November 30, 2024