Skip to content

Instantly share code, notes, and snippets.

@junaidtk
Created June 7, 2021 04:51
Show Gist options
  • Save junaidtk/d2068c292dc08e1f68e4d2e51ebda5b2 to your computer and use it in GitHub Desktop.
Save junaidtk/d2068c292dc08e1f68e4d2e51ebda5b2 to your computer and use it in GitHub Desktop.
Javascript
1)Get the last element of array:
===============================
let numbersArr = [4, 8, 9, 34, 100];
numbersArr[numbersArr.length - 1]; //return 100
2)Get a random number in a specific range:
=========================================
// Random number between 0 and 4.
Math.floor(Math.random() * 5);
// Random number between 0 and 49.
Math.floor(Math.random() * 50);
3)Convert a multidimensional array to single dimensional:
=========================================================
let arr = [5, [1, 2], [4, 8]];
arr.flat(); //returns [5, 1, 2, 4, 8]
let twoLevelArr = [4, ["John", 7, [5, 9]]]
twoLevelArr.flat(2); //returns [4, "John", 7, 5, 9]
4)To checkout multiple conditions:
==================================
let name = "John";
//Bad way.
if(name === "John" || name === "Ben" || name === "Chris"){
console.log("included")
}
//Better way.
if(["John", "Ben", "Chris"].includes(name)){
console.log("included")
}
5)To get unique value in array and remove the duplicate ones:
============================================================
const languages = ['JavaScript', 'Python', 'Python', 'JavaScript', 'HTML', 'Python'];
const uniqueLanguages = [...new Set(languages)];
console.log(uniqueLanguages);
//prints: ["JavaScript", "Python", "HTML"]
6)If you want run a event only once use below:
==============================================
document.body.addEventListener('click', () => {
console.log('Run only once');
}, { once: true });
7)Reduce method for summing all number in an array:
===================================================
ES6-method:
let numbers = [6, 9 , 90, 120, 55];
numbers.reduce((a, b)=> a + b, 0); //returns 280
ES5:
var arr = [29, 46, 86.5];
var sum = arr.reduce( function(total, value){
return total + value
});
console.log(sum); // 161.5
reduce()method will iterate all the element in an array.
total it is intila value or previuosly retruned value of the function.
value is the next vlaue in the array.
8)In operator:
===============
Used to check a property is defined in an obejct or an element is included inside an array.
const employee = {
name: "Chris",
age: 25
}
"name" in employee; //returns true.
"age" in employee; //returns true.
"experience" in employee; //retuens false.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment