Skip to content

Instantly share code, notes, and snippets.

View Jagathishrex's full-sized avatar
🎯
Focusing

Jagathishrex

🎯
Focusing
View GitHub Profile
function removeElement(arr, ele){
const index = arr.indexOf(2);
if (index > -1) {
arr.splice(index, 1);
}
}
const numbers = [1, 2, 3, 4];
removeElement(numbers, 2);
// print key-values of an object recursively
function flattenObject(obj) {
for (let key in obj) {
if (typeof obj[key] === 'string') {
console.log(key, obj[key]);
}
if (typeof obj[key] === 'object') {
flattenObject(obj[key]);
}
function reverseInt(n) {
let reversedInteger = n.toString().split('').reverse().join('');
return parseInt(reversedInteger) * Math.sign(n);
}
console.log(reverseInt(-12)); // -21
console.log(reverseInt(-1)); // -1
var a = [1,2,3];
var b = true;
var c = [4,5,6];
const concatAb = [].concat(a, b); // [1, 2, 3, true]
const concatAb = [].concat(a, b); // [1, 2, 3, 4, 5, 6]
sorting numbers
const arr = [1, 20, 8, 4, 9, 0];
//ascending order
arr.sort((a, b) => a - b); // [0, 1, 4, 8, 9, 20]
// Sort in descending order
arr.sort((a, b) => b - a); // [20, 9, 8, 4, 1, 0]
sorting string
const strArr = ['Java', 'Python', 'HTML', "css", "CSS"];
function hasDuplicates(array) {
let uniqueValues = new Set(array); // set --> contains only unique values
return uniqueValues.size !== array.length;
}
hasDupicates([1,2,3]); // false
hasDupicates([1,2,3,1]); // true
// Returns a random number(float) between min (inclusive) and max (exclusive)
const getRandomNumber = (min, max) => Math.random() * (max - min) + min;
getRandomNumber(2, 10)
// Returns a random number(int) between min (inclusive) and max (inclusive)
const getRandomNumberInclusive =(min, max)=> {
min = Math.ceil(min);

How to generate a random number in a given range

// Returns a random number(float) between min (inclusive) and max (exclusive) 

const getRandomNumber = (min, max) => Math.random() * (max - min) + min;

getRandomNumber(2, 10)

 // Returns a random number(int) between min (inclusive) and max (inclusive)
let num = new Array(3); // creating an empty array with length 3
console.log(num); // [empty × 3]
console.log(num[0]); // undefined
// the callback function passed to Array.some method will not check the callback for unassigned values
num.some(a => {console.log(a); return a === undefined }) // false
const lang = ["Java", "JavaScript"];
let hasJavaScript = function(currentElement, index, array){
console.log(`currentElement = ${currentElement}`);
console.log(`index = ${index}`);
console.log("-------------------------");
return array[index] === "JavaScript";
}
// element found in 1st index
lang.findIndex( hasJavaScript ); // 1