Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

JavaScript_Coding_Challenges_for_Interview__1745586295

The document contains a collection of JavaScript functions that perform various tasks, including string manipulation, mathematical calculations, and array operations. Each function is accompanied by example usage and expected output. The functions cover a wide range of topics such as reversing strings, checking for palindromes, generating Fibonacci series, and implementing sorting algorithms.

Uploaded by

akashsahu481999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

JavaScript_Coding_Challenges_for_Interview__1745586295

The document contains a collection of JavaScript functions that perform various tasks, including string manipulation, mathematical calculations, and array operations. Each function is accompanied by example usage and expected output. The functions cover a wide range of topics such as reversing strings, checking for palindromes, generating Fibonacci series, and implementing sorting algorithms.

Uploaded by

akashsahu481999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1.

Reverse a String​

function reverseString(string){
console.log(string.split("").reverse().join(""));
};
reverseString("Automation"); //Output: ‘noitamotuA’

2. Check for Palindrome

function palindrome(data){
let
result=(data==data.split("").reverse().join(""))?"Yes it
is a palindrome":"No it is not a palindrome";
return result;
};
console.log(palindrome("233"));
//Output: ‘No it is not a
palindrome’
console.log(palindrome("121"));
//Output: ‘Yes it is a palindrome’

3. Fibonacci Series

function toGetFibonacci(n){
let fibseries=[0,1];
for(let i=2;i<=n;i++){
fibseries.push(fibseries[i-1]+fibseries[i-2]);
}
return fibseries.slice(0,n);
}
console.log(toGetFibonacci(4)); //Output: [ 0, 1, 1, 2 ]

1
4. Factorial of a Number

function toGetFactorial(n,factorial=1){
if(n<0) return "Factorial is undefined for negative
integers";
for(let i=1;i<=n;i++){
factorial*=i;
}
return factorial;
};
console.log(toGetFactorial(5)); //Output: 120

5. Prime Number Check

function isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false; }
}
return true; }
console.log(isPrime(16)); //Output: false ​
console.log(isPrime(3)); //Output: true

2
6. Count Vowels and Consonants

function countVowelsANdConsonants( word,vowels="aeiou", ​


vowelscount=0, consonantscount=0){
for(char of word){
if(/[a-zA-Z]/.test(char)){
if(vowels.includes(char))
vowelscount+=1;
else
consonantscount+=1;
}
}
return `vowelscount:${vowelscount}
consonantscount:${consonantscount}`;
}
console.log(countVowelsANdConsonants("abeiou23kol56#$s"));
//Output: vowelscount:6 consonantscount:4

7. Sort an Array

function sortAnArray(numbers){
return numbers.sort();
}
console.log(sortAnArray([1,5,10])); //Output: [ 1, 10, 5 ]

3
8. Merge Two Arrays

function MergingArrays(array1,array2){
return array1.concat(array2);
};
console.log(MergingArrays([1,2,3,4],[5,6,7,8]));
//Output: [
1, 2, 3, 4,
5, 6, 7, 8
]

9. Find the Largest Element in an Array

function toFindLargestELement(array){
return Math.max(...array);
};
console.log(toFindLargestELement([1,2,3,4,5])); ​
//Output: 55

10. Remove Duplicates from an Array

function removeDuplicates(array){
let
filteredarray=array.filter((value,index,numbers)=>{return
numbers.indexOf(value)==index});
return filteredarray;
}
console.log(removeDuplicates([1,2,4,2,1]));
//Output: [ 1, 2, 4 ]

4
11. Check if a Number is Armstrong

function toCheckArmstrong(number){
let array=number.toString().split("").map(Number);
let
total=array.reduce((sum,value)=>sum+Math.pow(value,array.l
ength),0);
return result=total==number?"Is Armstrong":"Not
Armstrong";
};
console.log(toCheckArmstrong(153));
//Output: “is Armstrong”
console.log(toCheckArmstrong(121));
//Output: “not Armstrong”

12. Reverse a Number

function toReverseNumber(number){
let
reversednum=Number(Math.abs(number).toString().split("").r
everse().join(""));
return number<0?-reversednum:reversednum;
};
console.log(toReverseNumber(12345)); //Output: 54321
console.log(toReverseNumber(-12345)); //Output: -54321

5
13. Calculate GCD of Two Numbers

function toGetGCD(a,b){
while(b!=0){
let temp=b;
b=a%b;
a=temp;
}
return a;
};
console.log(toGetGCD(8,0)); //Output: 8

14. Check for Anagram

function checkAnagram(word1,word2){
let
string1=word1.replace(/\s/g,'').toLowerCase().split("").so
rt().join("");
let
string2=word2.replace(/\s/g,'').toLowerCase().split("").so
rt().join("");
return string1==string2?"Is Anagram":"Not
Anagram";
};
console.log(checkAnagram("Elbow","below"));
//Output: “Is Anagram”
console.log(checkAnagram("hello","hell"));
//Output: “Not Anagram”

6
15. Count the Number of Digits in a Number

function toCountDigits(number){
return (Math.abs(number).toString()).length;
};
console.log(toCountDigits(123)); //Output: 3
console.log(toCountDigits(-123)); //Output: 3

16. Print the Prime Numbers in a Range

function primeNumber(n,m){
let primenum=[];
for(i=n;i<=m;i++){
if(i<2) continue;
let isPrime=true;
for(j=2;j<=Math.sqrt(i);j++){
if(i%j==0){
isPrime=false;
break;
}
};
if(isPrime) primenum.push(i);
}
return primenum;
}
console.log(primeNumber(10,20)); //Output: [ 11, 13, 17,
19 ]

7
17. Find the Second Largest Element in an Array

function toFindSecondLargest(array){
return
array.length<2?"There is no largest element":
[...new Set(array)].sort((a,b)=>b-a)[1];
};
console.log(toFindSecondLargest([2,5,3,8,7,9,10]));
//Output: 9

18. Print the Pascal's Triangle

function pascalTriangle(rows){
const triangle=[];
for(let i=0;i<rows;i++) {
triangle[i]=[1];
for(let j=1;j<i;j++) {

triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
}
if (i>0) triangle[i].push(1);
}
for(let row of triangle){
console.log(...row); }
};
pascalTriangle(5); //Output: 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

8
19. Swap Two Numbers

function swapNumbers(a,b){
[a,b]=[b,a]
return [a,b];
};
console.log(swapNumbers(1,2)); //Output:[ 2, 1 ]

20. Find the Missing Number in an Array

function toFindMisingNumber(array){
let missnum=[];
let set=[...new Set(array)];
for(i=1;i<=Math.max(...array);i++){
if(!set.includes(i))
missnum.push(i);
}
return missnum;
};
console.log(toFindMisingNumber([1,3,4,5,7,9]));
//Output: [ 2, 6, 8 ]

21. Convert Decimal to Binary

function decimalToBinary(n){
let reminder=[];
while(n>0){
reminder.push(n%2);
n=Math.floor(n/2);
}
return Number(reminder.reverse().join(""));
}
console.log(decimalToBinary(13)); //Output: 1101

9
22. Check for Perfect Number

function checkForPerfectNum(n,sum=0){
for(i=1;i<n;i++){
if(n%i==0)
sum=sum+i;
}
return sum==n?"It is a Perfect number":"It is not a
Perfect number";
};
console.log(checkForPerfectNum(28));
//Output: “It is a Perfect number”
console.log(checkForPerfectNum(7));
//Output: “It is not a Perfect number”

23. Implementing a Simple Calculator

function simpleCalculator(a,b,sign){
if ((typeof a === "number") && (typeof b ===
"number")) {
switch (sign) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
}
}
return "unknown value";
};
console.log(simpleCalculator(1,2,"+")) //Output: 3

10
24. Find the Sum of Digits of a Number

function sumOfDigits(number,sum=0){
return
sum=number.toString().split("").reduce((add,value)=>add+Nu
mber(value),0);
};
console.log(sumOfDigits(12345)); //Output: 15

25. Find the Length of a String

function length(string){
return string.length;
};
console.log(length("kulsum")); //Output: 6

26. Check if a String is Empty

function emptyString(string){
if(string==="") return "string is empty";
};
console.log(emptyString("")); //Output: string is empty

27. Count the Occurrences of a Character in a String

function count(string,char){
return (string.match(char)).length;
};
console.log(count("karnataka",/a/g)); //Output: 4

11
28. Find the First Non-Repeated Character in a String

function nonRepeatChar(string){
for(char of string){
let regex=new RegExp(char,'gi');
if((string.match(regex)).length==1) return
char;
};
return null;
};
console.log(nonRepeatChar("MalaYalam")) //Output: Y

29. Remove All Whitespaces from a String

function removeWhite(string){
return string.replace(/\s/g,'');
};
console.log(removeWhite("a uto m obile"));
//Output: automobile

30. Find the Common Elements in Two Arrays

function commonElements(array1,array2){
return
array1.filter((value)=>array2.includes(value));
};
console.log(commonElements([1,2,3],[3,2,4,5]));
//Output: [ 2, 3 ]

12
31. Find the Factorial of a Number using Recursion

function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
console.log(factorial(5)); //Output: 120

32. Generate Random Numbers

function randomNumber(){
return Math.round(Math.random()*10000);
}
console.log(randomNumber()); //Output: 3170

33. Check if a Year is Leap Year

function leapYear(year){
return ((year%4==0 && year%100!=0) ||
(year%400==0)?true:false);
};
console.log(leapYear(1600)); //Output: true
console.log(leapYear(1600)); //Output: false

34. Find the Sum of First N Natural Numbers

function naturalNumber(n,sum=0){
for(i=1;i<=n;i++){
sum+=i
}
return sum;
};
console.log(naturalNumber(3)) //Output: 6

13
35. Implement a Simple Login System
1. Username
●​ Starts with USR in upper case
●​ Having -
●​ Til max length 4 that digit
2. Write a regex for password
●​ Should starts with alphaa-z
●​ One upper case should be there
●​ 4 digit should be there
●​ Special symbol #+- should

function validateLogin(username,password){
let nameregex=/^[A-Z].*\-\d{0,4}.*$/g;
let
passregex=/^[a-z](?=.*[A-Z])(?=.*\d{4,})(?=.*[#\+\-]).*$/g
;
let isusernamevalid= nameregex.test(username);
let ispasswordvalid=passregex.test(password);
if(isusernamevalid && ispasswordvalid){
console.log("Login successful!");
}else{
console.log("Login failed:");
if(!isusernamevalid) console.log("-
Invalid username format.");
if(!ispasswordvalid) console.log("-
Invalid password format.");
}
};
validateLogin("Kulsum211-ga","kulsum1234#U");
//Output: “Login successful!”
validateLogin("Kulsum211ga","kulsum1234#U");
//Output: Login failed:
- Invalid username format.

14
36. Check if a String Contains Another String

function stringCheck(string,substring){
return
string.toLowerCase().includes(substring.toLowerCase());
};
console.log(stringCheck("JavaScript","script"));
//Output: true
console.log(stringCheck("JavaScript",”hell”));
//Output: false

37. Find the Maximum Occurring Character in a String

function toGetMaxChar(string){
let maxlength=0;
let maxchar;
for(char of string){
let regex=new RegExp(char,'gi');
let maxarray=string.match(regex);
if(maxarray.length>maxlength){
maxlength=maxarray.length;
maxchar=maxarray[0];
}
}
return maxchar;
};
console.log(toGetMaxChar("hello")); //Output: l

15
38. Implementing Bubble Sort

function bubbleSort(array){
let n=array.length;
let swap;
for(let i=0; i<n-1; i++){
for(let j=0; j< n-1-i; j++){
if(array[j] > array[j+1]){
swap=array[j];
array[j]=array[j+1];
array[j+1]=swap;
}
}
}
return array;
};
console.log(bubbleSort([5,2,4,3,1]))
//Output: [ 1, 2, 3, 4, 5 ]

16
39. Implementing Selection Sort

function selectionSort(array){
let n=array.length;
let swap;
for(i=0;i<n-1;i++){
let minIndex=i;
for (j=i+1;j<n;j++){
if(array[j]< array[minIndex]){
minIndex=j;
}
}
if(minIndex!==i){
swap=array[i];
array[i]=array[minIndex];
array[minIndex]=swap;
}
}
return array;
};
console.log(selectionSort([5,2,4,3,1]));
//Output: [ 1, 2, 3, 4, 5 ]

17

You might also like