0% found this document useful (0 votes)
3 views

Javascript Module 9

Uploaded by

ANIME DRAWINGS
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)
3 views

Javascript Module 9

Uploaded by

ANIME DRAWINGS
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/ 12

Software Training and Placement Center

Basic Coding Questions

Basic Coding Questions on Strings:


Basic coding questions on strings often involve tasks such as checking for substring presence, reversing
strings, finding the length of strings, counting occurrences of characters, and so on.

1. Reverse a String
Question: Write a function to reverse a given string.
Code :

function reverseString(str) {
return str.split("").reverse().join("");
}

// Test the function


console.log(reverseString("hello")); // Output: olleh

2. Check Palindrome
Question: Write a function to determine if a string is a palindrome (reads the same forwards
and backwards).
Code :

function isPalindrome(str) {
const reversed = str.split("").reverse().join("");
return str === reversed;
}

// Test the function


console.log(isPalindrome("racecar")); // Output: true
console.log(isPalindrome("hello")); // Output: false

3. Count Vowels
Question: Write a function to count the number of vowels in a string.

Code :
function countVowels(str) {
const vowels = 'aeiou';
let count = 0;
for (let char of str.toLowerCase()) {
if (vowels.includes(char)) {
count++;
}

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

}
return count;
}

// Test the function


console.log(countVowels("hello")); // Output: 2

4. Capitalize Words
Question: Write a function to capitalize the first letter of each word in a sentence.
Code :
function capitalizeWords(sentence) {
return sentence.split(" ").map(word => word.charAt(0).toUpperCase()
+ word.slice(1)).join(" ");
}

// Test the function


console.log(capitalizeWords("hello world")); // Output: Hello
World

5. Check Anagrams
Question: Write a function to check if two strings are anagrams of each other.
Code :

function areAnagrams(str1, str2) {


const sortedStr1 = str1.split("").sort().join("");
const sortedStr2 = str2.split("").sort().join("");
return sortedStr1 === sortedStr2;
}

// Test the function


console.log(areAnagrams("listen", "silent")); // Output: true
console.log(areAnagrams("hello", "world")); // Output: false

6. Find Longest Word


Question: Write a function to find the longest word in a sentence.

Code :
function longestWord(sentence) {
const words = sentence.split(" ");
let longest = words[0];
for (let word of words) {
if (word.length > longest.length) {
longest = word;
}

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

}
return longest;
}

// Test the function


console.log(longestWord("hello world")); // Output: hello

7. Remove Duplicates
Question: Write a function to remove duplicate characters from a string.

Code :
function removeDuplicates(str) {
let result = "";
for (let char of str) {
if (result.indexOf(char) === -1) {
result += char;
}
}
return result;
}

// Test the function


console.log(removeDuplicates("hello")); // Output: helo

8. Count Characters
Question: Write a function to count the occurrences of each character in a string.
Code:
function countCharacters(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
return charCount;
}

// Test the function


console.log(countCharacters("hello")); // Output: { h: 1, e: 1, l: 2,
o: 1 }

9. Replace Spaces
Question: Write a function to replace all spaces in a string with '%20'.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

Code :
function replaceSpaces(str) {
return str.replace(/\s/g, '%20');
}

// Test the function


console.log(replaceSpaces("hello world")); // Output: hello%20world

10. Title Case


Question: Write a function to convert the first letter of each word in a sentence to uppercase.

Code :
function titleCase(sentence) {
return sentence.toLowerCase().replace(/(^|\s)\w/g, (match) =>
match.toUpperCase());
}

// Test the function


console.log(titleCase("hello world")); // Output: Hello World

11. Find Substring


Question: Write a function to check if a substring exists within a given string.

Code :
function hasSubstring(str, substr) {
return str.includes(substr);
}

// Test the function


console.log(hasSubstring("hello world", "world")); // Output: true
console.log(hasSubstring("hello world", "planet")); // Output: false

12. Remove Whitespace


Question: Write a function to remove all whitespace from a string.

Code :
function removeWhitespace(str) {
return str.replace(/\s/g, "");
}

// Test the function


console.log(removeWhitespace("hello world")); // Output: helloworld

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

13. Check Subsequence


Question: Write a function to check if a given string is a subsequence of another string.

Code :
function isSubsequence(sub, str) {
let subIndex = 0;
for (let char of str) {
if (char === sub[subIndex]) {
subIndex++;
}
if (subIndex === sub.length) {
return true;
}
}
return false;
}

// Test the function


console.log(isSubsequence("abc", "ahbgdc")); // Output: true
console.log(isSubsequence("axc", "ahbgdc")); // Output: false

14. Find First Non-Repeating Character


Question: Write a function to find the first non-repeating character in a string.

Code :
function firstNonRepeatingChar(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let char of str) {
if (charCount[char] === 1) {
return char;
}
}
return null;
}

// Test the function


console.log(firstNonRepeatingChar("hello")); // Output: h
console.log(firstNonRepeatingChar("hello world")); // Output: h
console.log(firstNonRepeatingChar("aabbcc")); // Output: null

15. Check Rotation

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

Question: Write a function to check if one string is a rotation of another string.

Code :
function isRotation(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
const combinedStr = str1 + str1;
return combinedStr.includes(str2);
}

// Test the function


console.log(isRotation("waterbottle", "erbottlewat")); // Output: true
console.log(isRotation("hello", "world")); // Output: false

16. . Count Words


Question: Write a function to count the number of words in a sentence.

Code :
function countWords(sentence) {
return sentence.split(" ").filter(word => word !== "").length;
}

// Test the function


console.log(countWords("Hello world")); // Output: 2
console.log(countWords("How are you today?")); // Output: 4

Basic Coding Questions on Arrays :


1. Find the sum of all elements in an array:
Code :
function sumArray(arr) {
let sum = 0;
for (let num of arr) {
sum += num;
}
return sum;
}

// Example usage:
const numbers = [1, 2, 3, 4, 5];
console.log(sumArray(numbers)); // Output: 15

2. Find the average of the array elements

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

Code :
function averageArray(arr) {
const sum = sumArray(arr);
return sum / arr.length;
}

function sumArray(arr) {
let sum = 0;
for (let num of arr) {
sum += num;
}
return sum;
}
const numbers = [1, 2, 3, 4, 5];
// Example usage:
console.log(averageArray(numbers)); // Output: 3

Checkout JS Fiddle Link


3. Find the maximum and the minimum element in an array
Code :
function findMaxMin(arr) {
let max = arr[0];
let min = arr[0];
for (let num of arr) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
return { max, min };
}
const numbers = [1, 2, 3, 4, 5];
// Example usage:
console.log(findMaxMin(numbers)); // Output: { max: 5, min: 1 }

Checkout JS Fiddle Link

4. Check if an array is in sorted order :


Code :
function isSorted(arr) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

}
}
return true;
}

const numbers = [1, 2, 3, 4, 5];


// Example usage:
console.log(isSorted(numbers)); // Output: true

Checkout the JS Fiddle Link

5. Find second largest number in an array


Code :

let arr =[1,24,7,33,8,1,33];

function secondLargest(arr){
let secondLargest =arr[0];
let largest = arr[0];
for(let element of arr){
if(largest< element){
secondLargest = largest;
largest = element
} else if(secondLargest < element && element!=largest){
secondLargest = element
}
}
return secondLargest
}
// Example usage

console.log(secondLargest(arr))

Checkout the JS Fiddle Link

6. Pattern Programs – Triangle Right Angle with Numbers -I


Sample :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Code :

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

// you can change the input rows based on your need


let rows = 5;

// pattern variable carries the final pattern in string format


let pattern = "";

// outer loop runs for `rows` no. of times


for (let n = 1; n <= rows; n++) {
// inner loop runs for n
for (let num = 1; num <= n; num++) {
pattern += num;
}

// Add a new line character after contents of each line


pattern += "\n";
}
console.log(pattern);

Checkout the JSFiddle Link Below

7. Pattern Programs – Triangle Right Angle with Numbers -II


Sample :

1
2 3
4 5 6
7 8 9 10

Code :
// you can chhanges the input as per as your input
let rows = 4;

// variable contains the next element of the pattern


let variable = 1;

// pattern variable carries the final pattern in string format


let pattern = "";

// outer loop runs for `rows` no. of times


for (let n = 1; n <= rows; n++) {
for (let num = 1; num <= n; num++) {
pattern += variable+" ";
variable++;
}
pattern += "\n";

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

}
console.log(pattern);

Checkout JS Fiddle Link

8. Pattern – Reverse Right Angular Triangle – I


Sample :
54321
5432
543
54
5

Code :
// you can change the size of row
let rows = 5;

// pattern variable carries the final pattern in string format


let pattern = "";

// outer loop runs for `rows` no. of times


for (let n = 1; n <= rows; n++) {
for (let num = rows; num >=n; num--) {
pattern += num;
}
pattern += "\n";
}
console.log(pattern);

Checkout JS Fiddle Link

9. Pattern Program – Equilateral Triangle – 1


Sample :
1
123
12345
1234567
123456789

Code :
// you can change the input by re-sizing the rows value
let rows = 5;

// pattern variable carries the final pattern in string format

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

let pattern = "";

// outer loop runs for `rows` no. of times


for (let n = 1; n <= rows; n++) {
// Inner Loop - I -> for the spaces
for (let space = 1; space <= rows - n; space++) {
pattern += " ";
}

// Inner Loop - II -> for the numbers


for (let num = 1; num <= 2 * n - 1; num++) {
pattern += num;
}

pattern += "\n";
}
console.log(pattern);

Checkout JS Fiddle Link

10. Print Square Pattern -1


Sample :
*****
*****
*****
*****
*****

Code :

// you can change the input size


let rows = 5;

// pattern variable carries the final pattern in string format


let pattern = "";

// outer loop runs for `rows` no. of times


for (let n = 1; n <= rows; n++) {
// Inner loop for printing stars
for (let num = 1; num <= 5; num++) {
pattern += "*";
}
pattern += "\n";
}

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in
Software Training and Placement Center

console.log(pattern);

Checkout the JS Fiddle Link

11. Print Square Pattern -2


Sample :
*****
* *
* *
* *
*****

Code :
// modify value as per the requirement
let rows = 5;

// pattern variable carries the final pattern in string format


let pattern = "";

// outer loop runs for `rows` no. of times


for (let n = 1; n <= rows; n++) {
for (let num = 1; num <= 5; num++) {
// print star only if it is the boundary location
if (n == 1 || n == rows) pattern += "*";
else {
if (num == 1 || num == 5) {
pattern += "*";
} else {
pattern += " ";
}
}
}
pattern += "\n";
}
console.log(pattern);

Checkout the JS Fiddle Link

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : enquries@bytesplash.in

You might also like