Welcome Guys, its me Md Taqui Imam . So in Today's Blog i will tell you 07 most use cases JavaScript One-Liner Code that use will save your time, code base size and make your code look like a Pro.
So, let's begin and don't forget to Drop a Like (๐ฅ๐๐ฆ๐๐คฏ) and Save it for later ๐.
If you have any doubt then feel Free to Contact Me ๐ฉ.
1. Find Value in Array ๐
Let's start with Basic One-Liner of how to Check if an Array contain a value or not.
// Array
const MyArray = [12,55,40,78,5];
// One-liner
const haveValue = arr => arr.includes(5);
// Test
console.log("Answer ", haveValue(MyArray)) // Answer true
This is the one-liner to see Array contain a Particular value or not. You can modify accourding to your needs.
2. Object Deep Clone ๐
This one-Liner will make a Deep clone of your object:
const myObj = {
"name": "Md Taqui Imam",
"age": 22,
"country": "india"
};
const deepClone = obj => JSON.parse(JSON.stringify(obj));
console.log("Answer ", deepClone(myObj));
// Answer Object {"name": "Md Taqui Imam","age": 22,"country": "india"}
3. Scroll To Top ๐
This is the One-Liner that instantly navigates you to the Top of the Page :
window.scrollTo(0, 0) // navigate to Top
4. Truncate a String To a Specific Length "..."โญ
This One-Liner is to Truncate a String and add "..." to an End on a specific given Length :
const myString = "Lorem ipsum is simply dummy text of the printing and typesetting industry.";
const truncate = (str, len) => str?.length > len ? str.slice(0, len) + "..." : str;
console.log("Answer", truncate(myString, 52));
// Answer Lorem ipsum is simply dummy text of the printing and...
5. Remove Dublicated item in ๐ [ ]
This one-Liner will return a new Array without repeating dublicated item from an Array :
const myArr = [4,8,3,9,4];
const dublicate = arr => [...new Set(arr)]
console.log("Answer ", dublicate(myArr));
// Answer (4) [4, 8, 3, 9]
6. Check all are same ๐ค or not
This one-liner will help you to check that all item of an Array are same/identical or Not :
const myArr = [4,4,4,4,4];
const allSame = arr => arr.every(val => val === arr[0]);
console.log("Answer ", allSame(myArr));
// Answer true
7. Get last item from ๐ [ ]
Now, Last one-liner will help you to get the last item of an array :
const myArr = [4,8,2,9,1,6];
const lastItm = arr => arr[arr.length - 1];
console.log("Answer", lastItm(myArr));
// Answer 6
End ๐
I hope you find this Blog post heplful and these 7 one-liners will help you to make your code base size smaller, and boost you productivity.
See you in next Blog๐ and don't forget to subscribe the newsletter๐ฉ