Ditching Dependencies: You don't need libraries for these JavaScript tasks

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);
// 29Flatten 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 });
// trueSlugify a string
const slugify = (str) =>
str
.toLowerCase()
.replace(/[^\w ]+/g, "")
.replace(/ +/g, "-");
slugify("Hello World");
// hello-worldIf you enjoyed this article, please share it with your friends and colleagues. If you have any questions or suggestions, please leave a comment below.
Comments
Keep reading

Improving Angular Performance: Using Decorators to Track Method Invocations
I was working on an old Angular project and I noticed that the developer was calling a lot of functions inside the template. The template was full of functions like this:

Why You Should Disable Source Maps in Production
Sourcemap is a powerful tool for developers when debugging their JavaScript code. They provide a way to map the minified, production code back to the original, unminified source…

A Beginner's Guide to MutationObserver in JavaScript
MutationObserver is a powerful feature in modern web development that allows developers to monitor changes in the DOM and execute custom logic in response. In this post, we'll…