CodeGym Đà Nẵng
  • Khoá học
    • Khóa AI Engineer
    • Java Web Fulltime
    • Java Web Fullstack Parttime
    • Python Web Fulltime
    • >>Xem tất cả khóa học
  • Lịch khai giảng
  • Blog lập trình
    • Kiến thức chuyên môn
    • Tin công nghệ
  • Tin tức
    • Học viên
    • Tuyển dụng
  • Về chúng tôi
    • Tại sao nên chọn CodeGym Đà Nẵng
    • Thông tin tuyển sinh
    • Mô hình Coding Bootcamp
    • Báo chí nói gì?
    • Câu hỏi thường gặp
    • Hình ảnh hoạt động
    • Đối tác tuyển dụng
    • Thông tin liên hệ
Chọn trang

150+ bài tập JavaScript cơ bản kèm lời giải chi tiết

11/09/2025 | Bài tập lập trình | 0 Lời bình

Trang chủ » Bài tập lập trình » 150+ bài tập JavaScript cơ bản kèm lời giải chi tiết

Bạn đang tìm bài tập JavaScript để rèn luyện kỹ năng và làm quen với những thử thách thực tế? Đây chính là “mảnh đất màu mỡ” để bạn vừa học vừa áp dụng ngay, từ đó tăng tốc con đường trở thành lập trình viên chuyên nghiệp. Đừng lo nếu bạn còn là “newbie”, những thử thách nhỏ sẽ giúp bạn vững vàng hơn từng bước. Và… hãy cùng CodeGym Đà Nẵng khám phá ở bài viết dưới đây!

Nội dung

  • JavaScript là gì?
  • Vì sao nên học JavaScript?
  • Tổng hợp bài tập JavaScript cơ bản có đáp án

JavaScript là gì?

JavaScript là một ngôn ngữ lập trình hướng đối tượng, có khả năng chạy trên nhiều nền tảng khác nhau. Đây là ngôn ngữ gọn nhẹ, linh hoạt và dễ tích hợp. Khi hoạt động trong môi trường host (như trình duyệt web), JavaScript có thể tương tác với các đối tượng của môi trường đó, giúp lập trình viên điều khiển chúng bằng mã lệnh.

Ngoài ra, JavaScript còn cung cấp thư viện chuẩn gồm nhiều đối tượng hữu ích như mảng, ngày tháng, toán học, cùng với các thành phần ngôn ngữ cơ bản như toán tử, cấu trúc điều khiển và câu lệnh.

bài tập javascript

JavaScript biến trang web tĩnh thành trải nghiệm sống động chỉ với vài dòng code (Nguồn: Internet)

Vì sao nên học JavaScript?

Khi học JavaScript, bạn không chỉ tiếp cận một ngôn ngữ phổ biến mà còn nhận về nhiều lợi ích thiết thực:

  • Tương thích tốt với trình duyệt: JavaScript là ngôn ngữ “mặc định” của Internet, cho phép bạn dễ dàng viết, chạy và kiểm tra mã nguồn ngay trên trình duyệt. Chỉ cần một công cụ soạn thảo như VSCode hay Sublime Text, bạn đã có thể bắt tay vào lập trình ngay lập tức.
  • Đa năng trong ứng dụng: Không chỉ phục vụ lập trình web, JavaScript còn được sử dụng rộng rãi ở nhiều lĩnh vực khác như Frontend, Backend, phát triển ứng dụng di động, game hay thậm chí cả lưu trữ dữ liệu trên nền tảng đám mây.
  • Kho tài nguyên phong phú: Đây là ngôn ngữ có cộng đồng đông đảo và tài nguyên cực kỳ dồi dào. Bạn có thể tìm thấy vô số tài liệu, công cụ, giải pháp trên các nền tảng nổi tiếng như GitHub, GeeksforGeeks, StackOverflow hay Hashnode để luôn bắt kịp xu hướng công nghệ.
  • Dễ tiếp cận cho người mới: JavaScript được đánh giá là ngôn ngữ thân thiện, dễ học, không đòi hỏi công cụ phức tạp và có thể chạy trực tiếp trong trình duyệt, rất phù hợp cho những ai mới bắt đầu hành trình lập trình.
  • Mở rộng cơ hội nghề nghiệp: Việc thành thạo JavaScript giúp bạn gia tăng lợi thế cạnh tranh trong thị trường lao động. Bên cạnh đó, nếu nắm thêm các framework hiện đại như React.js hay Node.js, bạn sẽ có nhiều cơ hội thăng tiến và phát triển sự nghiệp hơn nữa.

Tổng hợp bài tập JavaScript cơ bản có đáp án

1. Hiển thị ngày và giờ hiện tại
Viết chương trình JavaScript hiển thị ngày và thời gian hệ thống theo định dạng mẫu.
Ví dụ: Hôm nay là Thứ Ba. Giờ hiện tại: 10 giờ tối : 30 : 38.

Code mẫu:

// Get the current date and time
var today = new Date();

// Get the day of the week (0-6, where 0 is Sunday and 6 is Saturday)
var day = today.getDay();

// Array of day names
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

// Display the current day
console.log("Today is: " + daylist[day] + ".");

// Get the current hour, minute, and second
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();

// Determine if it's AM or PM
var prepand = (hour >= 12) ? " PM " : " AM ";

// Convert 24-hour format to 12-hour format
hour = (hour >= 12) ? hour - 12 : hour;

// Check for special cases when hour is 0
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}

// Check for special cases when hour is 0
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}

// Display the current time
console.log("Current Time: " + hour + prepand + " : " + minute + " : " + second);

2. In toàn bộ nội dung cửa sổ
Tạo chương trình JavaScript in ra nội dung trang web hiện tại.

Code mẫu:

// Define a function named print_current_page
function print_current_page() {
// Call the window.print() method to initiate the printing of the current page
window.print();
} 

3. Lấy ngày hiện tại theo nhiều kiểu
Viết chương trình JavaScript lấy ngày hôm nay và hiển thị dưới các định dạng:
mm-dd-yyyy, mm/dd/yyyy, dd-mm-yyyy, dd/mm/yyyy.

Code mẫu:

// Get the current date
var today = new Date();

// Get the day of the month
var dd = today.getDate();

// Get the month (adding 1 because months are zero-based)
var mm = today.getMonth() + 1;

// Get the year
var yyyy = today.getFullYear();

// Add leading zero if the day is less than 10
if (dd < 10) {
dd = '0' + dd;
} 

// Add leading zero if the month is less than 10
if (mm < 10) {
mm = '0' + mm;
} 

// Format the date as mm-dd-yyyy and log it
today = mm + '-' + dd + '-' + yyyy;
console.log(today);

// Format the date as mm/dd/yyyy and log it
today = mm + '/' + dd + '/' + yyyy;
console.log(today);

// Format the date as dd-mm-yyyy and log it
today = dd + '-' + mm + '-' + yyyy;
console.log(today);

// Format the date as dd/mm/yyyy and log it
today = dd + '/' + mm + '/' + yyyy;
console.log(today);

4. Tính diện tích tam giác (cạnh 5, 6, 7)
Viết chương trình JavaScript tính diện tích tam giác với ba cạnh 5, 6, 7.

Code mẫu:

// Define the lengths of the three sides of a triangle
var side1 = 5; 
var side2 = 6; 
var side3 = 7; 

// Calculate the semi-perimeter of the triangle
var s = (side1 + side2 + side3) / 2;

// Use Heron's formula to calculate the area of the triangle
var area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3)));

// Log the calculated area to the console
console.log(area);

5. Xoay vòng chuỗi ‘w3resource’
Tạo chương trình JavaScript định kỳ xoay chuỗi bằng cách chuyển ký tự cuối lên đầu.

Code mẫu:

// Define a function that animates the characters of a string
function animate_string(id) {
// Get the HTML element by its id

var element = document.getElementById(id);
// Access the text node inside the element (assuming no other children)
var textNode = element.childNodes[0]; 

// Extract the initial text content of the text node
var text = textNode.data;

// Set up an interval to rotate the characters in the text every 100 milliseconds
setInterval(function () {
// Move the last character to the beginning of the string
text = text[text.length - 1] + text.substring(0, text.length - 1);

// Update the text content of the text node with the modified string
textNode.data = text;
}, 100);
} 

6. Kiểm tra năm nhuận (theo lịch Gregory)
Viết hàm JavaScript xác định một năm có phải năm nhuận hay không.

Code mẫu:

 // Define a function to check if a given year is a leap year
function leapyear(year) {
// Return true if the year is divisible by 4 but not divisible by 100 unless it's also divisible by 400
return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}

// Test the function with various years and log the results to the console
console.log(leapyear(2016)); // Expected output: true
console.log(leapyear(2000)); // Expected output: true
console.log(leapyear(1700)); // Expected output: false
console.log(leapyear(1800)); // Expected output: false
console.log(leapyear(100)); // Expected output: false

7. Tìm năm có ngày 1/1 là Chủ Nhật (2014–2050)
Lập trình JavaScript để kiểm tra những năm từ 2014 đến 2050 mà ngày 1/1 rơi vào Chủ Nhật.

Code mẫu:

// Log a separator to visually distinguish the output
console.log('--------------------');

// Loop through the years from 2014 to 2050 (inclusive)
for (var year = 2014; year <= 2050; year++) {
// Create a Date object for January 1st of the current year
var d = new Date(year, 0, 1);

// Check if January 1st is a Sunday (where Sunday corresponds to day index 0)
if (d.getDay() === 0) {
// Log a message if January 1st is a Sunday for the current year
console.log("1st January is being a Sunday " + year);
}
}

// Log another separator to conclude the output
console.log('--------------------'); 

8. Trò chơi đoán số
Chương trình JavaScript sinh số ngẫu nhiên từ 1 đến 10, người dùng nhập dự đoán. Đúng → báo “Tốt”, sai → báo “Không khớp”.

Code mẫu:

// Generate a random integer between 1 and 10 (inclusive)
var num = Math.ceil(Math.random() * 10);

// Log the generated random number to the console
console.log(num);

// Prompt the user to guess a number between 1 and 10 (inclusive)
var gnum = prompt('Guess the number between 1 and 10 inclusive');

// Check if the guessed number matches the generated random number
if (gnum == num)
// Log a message if the guessed number matches the random number
console.log('Matched');
else
// Log a message if the guessed number does not match, and also provide the correct number
console.log('Not matched, the number was ' + gnum); 

9. Đếm ngày còn lại đến Giáng Sinh
Viết chương trình JavaScript tính số ngày còn lại trước Giáng Sinh.

Code mẫu:

// Get the current date
today = new Date();

// Create a Date object for Christmas of the current year
var cmas = new Date(today.getFullYear(), 11, 25);

// Check if the current date is after December 25th
if (today.getMonth() == 11 && today.getDate() > 25) {
// If true, set Christmas for the next year
cmas.setFullYear(cmas.getFullYear() + 1);
}
 
// Calculate the difference in days between today and Christmas
var one_day = 1000 * 60 * 60 * 24;

// Log the number of days left until Christmas to the console
console.log(Math.ceil((cmas.getTime() - today.getTime()) / (one_day)) +
" days left until Christmas!"); 

10. Tính nhân và chia (dữ liệu nhập từ người dùng)
Chương trình JavaScript cho phép nhập hai số rồi thực hiện phép nhân và chia.

Code mẫu:

<!DOCTYPE html>
<html> 
<head>
<meta charset=utf-8 />
<title>JavaScript program to calculate multiplication and division of two numbers </title>
<style type="text/css">
body {margin: 30px;}
</style> 
</head>
<body>
<form>
1st Number : <input type="text" id="firstNumber" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
<input type="button" onClick="divideBy()" Value="Divide" />
</form>
<p>The Result is : <br>
<span id = "result"></span>
</p>
</body>
</html>

11. Chuyển đổi nhiệt độ (C ↔ F)
Viết chương trình JavaScript chuyển đổi nhiệt độ giữa độ C và độ F.
Ví dụ:
60°C = 140°F
45°F = 7.22°C

Code mẫu:

// Define a function to convert Celsius to Fahrenheit
function cToF(celsius) {
// Store the input Celsius temperature in a variable
var cTemp = celsius;

// Calculate the equivalent Fahrenheit temperature
var cToFahr = cTemp * 9 / 5 + 32;

// Create a message string describing the conversion result
var message = cTemp + '\xB0C is ' + cToFahr + ' \xB0F.';

// Log the message to the console
console.log(message);
}

// Define a function to convert Fahrenheit to Celsius
function fToC(fahrenheit) {
// Store the input Fahrenheit temperature in a variable
var fTemp = fahrenheit;

// Calculate the equivalent Celsius temperature
var fToCel = (fTemp - 32) * 5 / 9;

// Create a message string describing the conversion result
var message = fTemp + '\xB0F is ' + fToCel + '\xB0C.';

// Log the message to the console
console.log(message);
}

// Call the cToF function with a Celsius temperature of 60
cToF(60);

// Call the fToC function with a Fahrenheit temperature of 45
fToC(45); 

12. Lấy URL hiện tại của trang web
Chương trình JavaScript in ra URL của trang đang tải.

Code mẫu:

// Log the current website URL to the console
alert(document.URL);

13. Tạo biến với tên do người dùng định nghĩa
Viết chương trình JavaScript cho phép tạo biến bằng tên mà người dùng nhập vào.

Code mẫu:

// Declare a variable named var_name and assign it the string 'abcd'
var var_name = 'abcd';

// Declare a variable named n and assign it the number 120
var n = 120;

// Assign the value of n to the property named 'abcd' of the 'this' object
this[var_name] = n;

// Log the value of the property 'abcd' of the 'this' object to the console
console.log(this[var_name]); 

14. Lấy phần mở rộng của tệp
Viết chương trình JavaScript xác định phần mở rộng (đuôi) của một file.

Code mẫu:

// Assign the string "system.php" to the variable filename
filename = "system.php";

// Log the result of extracting the file extension using split and pop to the console
console.log(filename.split('.').pop());

// Reassign the variable filename to the string "abc.js"
filename = "abc.js";

// Log the result of extracting the file extension using split and pop to the console
console.log(filename.split('.').pop()); 

15. Hiệu giữa số bất kỳ và 13
Viết chương trình JavaScript tính hiệu với 13. Nếu số lớn hơn 13 thì trả về gấp đôi hiệu tuyệt đối.

Code mẫu:

// Define a function named difference that takes a parameter n
function difference(n) {
// Check if n is less than or equal to 13
if (n <= 13) {
// If true, return the difference between 13 and n
return 13 - n;
} else {
// If false, return the double of the difference between n and 13
return (n - 13) * 2;
}
}

// Log the result of calling the difference function with the argument 32 to the console
console.log(difference(32));

// Log the result of calling the difference function with the argument 11 to the console
console.log(difference(11)); 

16. Tính tổng 2 số nguyên (gấp 3 nếu giống nhau)
Chương trình JavaScript cộng hai số nguyên. Nếu chúng bằng nhau thì nhân 3 tổng.

Code mẫu:

// Define a function named sumTriple that takes two parameters, x and y
function sumTriple(x, y) {
// Check if x is equal to y
if (x == y) {
// If true, return three times the sum of x and y
return 3 * (x + y);
} else {
// If false, return the sum of x and y
return (x + y);
}
}

// Log the result of calling the sumTriple function with the arguments 10 and 20 to the console
console.log(sumTriple(10, 20));

// Log the result of calling the sumTriple function with the arguments 10 and 10 to the console
console.log(sumTriple(10, 10)); 

17. Hiệu tuyệt đối với 19 (gấp 3 nếu >19)
Viết chương trình JavaScript tính hiệu tuyệt đối với 19. Nếu số >19 thì trả về gấp 3.

Code mẫu:

// Define a function named diff_num that takes a parameter n
function diff_num(n) {
// Check if n is less than or equal to 19
if (n <= 19) {
// If true, return the difference between 19 and n
return (19 - n);
} else {
// If false, return three times the difference between n and 19
return (n - 19) * 3;
}
}

// Log the result of calling the diff_num function with the argument 12 to the console
console.log(diff_num(12));

// Log the result of calling the diff_num function with the argument 19 to the console
console.log(diff_num(19));

// Log the result of calling the diff_num function with the argument 22 to the console
console.log(diff_num(22)); 

18. Kiểm tra số hoặc tổng bằng 50
Chương trình JavaScript trả về true nếu một số là 50 hoặc tổng của hai số bằng 50.

Code mẫu:

// Define a function named test50 that takes two parameters, x and y
function test50(x, y) {
// Return true if x is equal to 50 or y is equal to 50 or the sum of x and y is equal to 50; otherwise, return false
return ((x == 50 || y == 50) || (x + y == 50));
}

// Log the result of calling the test50 function with the arguments 50 and 50 to the console
console.log(test50(50, 50));

// Log the result of calling the test50 function with the arguments 20 and 50 to the console
console.log(test50(20, 50));

// Log the result of calling the test50 function with the arguments 20 and 20 to the console
console.log(test50(20, 20));

// Log the result of calling the test50 function with the arguments 20 and 30 to the console
console.log(test50(20, 30));

19. Kiểm tra số nguyên nằm trong khoảng 20 của 100 hoặc 400
Viết chương trình JavaScript để xem một số có nằm trong phạm vi ±20 của 100 hoặc 400 không.

Code mẫu:

// Define a function named testhundred that takes a parameter x
function testhundred(x) {
// Return true if the absolute difference between 100 and x is less than or equal to 20,
// or the absolute difference between 400 and x is less than or equal to 20; otherwise, return false
return ((Math.abs(100 - x) <= 20) || (Math.abs(400 - x) <= 20));
}

// Log the result of calling the testhundred function with the argument 10 to the console
console.log(testhundred(10));

// Log the result of calling the testhundred function with the argument 90 to the console
console.log(testhundred(90));

// Log the result of calling the testhundred function with the argument 99 to the console
console.log(testhundred(99));

// Log the result of calling the testhundred function with the argument 199 to the console
console.log(testhundred(199));

// Log the result of calling the testhundred function with the argument 200 to the console
console.log(testhundred(200));

20. Kiểm tra số nguyên dương và âm
Viết chương trình JavaScript để xác định trong hai số nguyên cho trước, một số là dương và số còn lại là âm.

Code mẫu:

// Define a function named positive_negative that takes two parameters, x and y
function positive_negative(x, y) {
// Check if either x is negative and y is positive, or x is positive and y is negative
if ((x < 0 && y > 0) || (x > 0 && y < 0)) {
// If true, return true
return true;
} else {
// If false, return false
return false;
}
}

// Log the result of calling the positive_negative function with the arguments 2 and 2 to the console
console.log(positive_negative(2, 2));

// Log the result of calling the positive_negative function with the arguments -2 and 2 to the console
console.log(positive_negative(-2, 2));

// Log the result of calling the positive_negative function with the arguments 2 and -2 to the console
console.log(positive_negative(2, -2));

// Log the result of calling the positive_negative function with the arguments -2 and -2 to the console
console.log(positive_negative(-2, -2)); 

21. Thêm tiền tố “Py” vào chuỗi
Viết chương trình JavaScript để thêm “Py” vào đầu chuỗi. Nếu chuỗi đã bắt đầu bằng “Py”, trả về chuỗi ban đầu.

Code mẫu:

 // Define a function named string_check that takes a parameter str1
function string_check(str1) {
// Check if str1 is null, undefined, or starts with the substring 'Py'
if (str1 === null || str1 === undefined || str1.substring(0, 2) === 'Py') {
// If true, return str1
return str1;
}

// If false, prepend 'Py' to str1 and return the result
return "Py" + str1;
}
// Log the result of calling the string_check function with the argument "Python" to the console
console.log(string_check("Python"));

// Log the result of calling the string_check function with the argument "thon" to the console
console.log(string_check("thon"));

22. Xóa ký tự tại vị trí chỉ định
Viết chương trình JavaScript để loại bỏ ký tự ở một vị trí xác định trong chuỗi, sau đó trả về chuỗi mới.

Code mẫu:

// Define a function named remove_character that takes two parameters, str and char_pos
function remove_character(str, char_pos) {
// Extract the substring from the beginning of str up to (but not including) char_pos
part1 = str.substring(0, char_pos);
// Extract the substring from char_pos + 1 to the end of str
part2 = str.substring(char_pos + 1, str.length);
// Return the concatenation of part1 and part2, effectively removing the character at char_pos
return (part1 + part2);
}

// Log the result of calling the remove_character function with the arguments "Python" and 0 to the console
console.log(remove_character("Python", 0));

// Log the result of calling the remove_character function with the arguments "Python" and 3 to the console
console.log(remove_character("Python", 3));

// Log the result of calling the remove_character function with the arguments "Python" and 5 to the console
console.log(remove_character("Python", 5)); 

23. Đổi vị trí ký tự đầu và cuối
Viết chương trình JavaScript để tạo chuỗi mới bằng cách hoán đổi ký tự đầu tiên và cuối cùng. Yêu cầu độ dài chuỗi ≥ 1.

Code mẫu:

// Define a function named first_last that takes a parameter str1
function first_last(str1) {
// Check if the length of str1 is less than or equal to 1
if (str1.length <= 1) {
// If true, return str1 as is
return str1;
}
// Extract the substring from the second character to the second-to-last character of str1
mid_char = str1.substring(1, str1.length - 1);
// Return the last character of str1 followed by mid_char and then the first character of str1
return (str1.charAt(str1.length - 1)) + mid_char + str1.charAt(0);
}

// Log the result of calling the first_last function with the argument 'a' to the console
console.log(first_last('a'));

// Log the result of calling the first_last function with the argument 'ab' to the console
console.log(first_last('ab'));
// Log the result of calling the fi
rst_last function with the argument 'abc' to the console
console.log(first_last('abc')); 

24. Thêm ký tự đầu vào trước và sau chuỗi
Viết chương trình JavaScript để lấy ký tự đầu tiên của chuỗi và chèn thêm vào cả đầu và cuối chuỗi.

Code mẫu:

// Define a function named front_back that takes a parameter str
function front_back(str) {
// Extract the first character of str
first = str.substring(0, 1);
// Return the concatenation of first, str, and first
return first + str + first;
}

// Log the result of calling the front_back function with the argument 'a' to the console
console.log(front_back('a'));

// Log the result of calling the front_back function with the argument 'ab' to the console
console.log(front_back('ab'));

// Log the result of calling the front_back function with the argument 'abc' to the console
console.log(front_back('abc')); 

25. Kiểm tra bội số của 3 hoặc 7
Viết chương trình JavaScript để kiểm tra xem một số dương có phải bội số của 3 hoặc 7 hay không.

Code mẫu:

// Define a function named test37 that takes a parameter x
function test37(x) {
// Check if x is divisible by 3 or 7
if (x % 3 == 0 || x % 7 == 0) {
// If true, return true
return true;
} 
// If not divisible by 3 or 7, return false
else {
return false;
}
}

// Log the result of calling the test37 function with the argument 12 to the console
console.log(test37(12));

// Log the result of calling the test37 function with the argument 14 to the console
console.log(test37(14));

// Log the result of calling the test37 function with the argument 10 to the console
console.log(test37(10));

// Log the result of calling the test37 function with the argument 11 to the console
console.log(test37(11)); 

26. Thêm 3 ký tự cuối vào đầu và cuối chuỗi
Viết chương trình JavaScript tạo chuỗi mới bằng cách lấy 3 ký tự cuối của chuỗi gốc rồi thêm vào cả hai đầu. Yêu cầu độ dài ≥ 3.

Code mẫu:

// Define a function named front_back3 that takes a parameter str
function front_back3(str) {
// Check if the length of str is greater than or equal to 3
if (str.length >= 3) {
// Set str_len to 3
str_len = 3;
// Extract the last three characters of str
back = str.substring(str.length - 3);
// Return the concatenation of back, str, and back
return back + str + back;
} else {
// If the length of str is less than 3, return false
return false;
}
}

// Log the result of calling the front_back3 function with the argument "abc" to the console
console.log(front_back3("abc"));

// Log the result of calling the front_back3 function with the argument "ab" to the console
console.log(front_back3("ab"));

// Log the result of calling the front_back3 function with the argument "abcd" to the console
console.log(front_back3("abcd")); 

27. Chuỗi có bắt đầu bằng “Java” không
Viết chương trình JavaScript để kiểm tra một chuỗi có bắt đầu bằng từ “Java” hay không.

Code mẫu:

// Define a function named start_spec_str that takes a parameter str
function start_spec_str(str) {
// Check if the length of str is less than 4
if (str.length < 4) {
// If true, return false
return false;
}
// Extract the first four characters of str
front = str.substring(0, 4);
// Check if front is equal to 'Java'
if (front == 'Java') {
// If true, return true
return true;
} else {
// If not equal to 'Java', return false
return false;
}
}

// Log the result of calling the start_spec_str function with the argument "JavaScript" to the console
console.log(start_spec_str("JavaScript"));

// Log the result of calling the start_spec_str function with the argument "Java" to the console
console.log(start_spec_str("Java"));

// Log the result of calling the start_spec_str function with the argument "Python" to the console
console.log(start_spec_str("Python")); 

28. Hai số nguyên trong khoảng 50–99
Viết chương trình JavaScript để kiểm tra xem hai số nguyên cho trước có thuộc phạm vi từ 50 đến 99 không. Trả về true nếu có ít nhất một số nằm trong khoảng.

Code mẫu:

// Define a function named check_numbers that takes two parameters x and y
function check_numbers(x, y) {
// Check if x or y is in the range between 50 and 99 (inclusive)
if ((x >= 50 && x <= 99) || (y >= 50 && y <= 99)) {
// If true, return true
return true;
} else {
// If not in the specified range, return false
return false;
}
}

// Log the result of calling the check_numbers function with the arguments 12 and 101 to the console
console.log(check_numbers(12, 101));

// Log the result of calling the check_numbers function with the arguments 52 and 80 to the console
console.log(check_numbers(52, 80));

// Log the result of calling the check_numbers function with the arguments 15 and 99 to the console
console.log(check_numbers(15, 99)); 

29. Ba số nguyên trong khoảng 50–99
Viết chương trình JavaScript để kiểm tra xem ba số nguyên cho trước có số nào nằm trong khoảng từ 50 đến 99 không.

Code mẫu:

// Define a function named check_three_nums that takes three parameters x, y, and z
function check_three_nums(x, y, z) {
// Check if at least one of the numbers is in the range between 50 and 99 (inclusive)
return (x >= 50 && x <= 99) || (y >= 50 && y <= 99) || (z >= 50 && z <= 99);
}

// Log the result of calling the check_three_nums function with the arguments 50, 90, and 99 to the console
console.log(check_three_nums(50, 90, 99));

// Log the result of calling the check_three_nums function with the arguments 5, 9, and 199 to the console
console.log(check_three_nums(5, 9, 199));

// Log the result of calling the check_three_nums function with the arguments 65, 89, and 199 to the console
console.log(check_three_nums(65, 89, 199));

// Log the result of calling the check_three_nums function with the arguments 65, 9, and 199 to the console
console.log(check_three_nums(65, 9, 199)); 

30. Xóa “Script” tại vị trí thứ 5
Viết chương trình JavaScript để kiểm tra xem “Script” có xuất hiện ở vị trí thứ 5 (chỉ mục 4) trong chuỗi không. Nếu có, trả về chuỗi loại bỏ phần “Script”, nếu không thì trả về chuỗi gốc.

Code mẫu:

// Define a function named check_script that takes a string parameter str
function check_script(str) {
// Check if the length of the string is less than 6
if (str.length < 6) {
// If true, return the original string as it is
return str;
}

// Initialize a variable result_str with the value of the input string
let result_str = str;

// Check if the substring from index 10 to index 4 (exclusive) is equal to 'Script'
if (str.substring(10, 4) == 'Script') {
// If true, update result_str to exclude the substring 'Script' from index 4 to the end
result_str = str.substring(0, 4) + str.substring(10, str.length);
}

// Return the final result_str
return result_str;
}

// Log the result of calling check_script with the argument "JavaScript" to the console
console.log(check_script("JavaScript"));

// Log the result of calling check_script with the argument "CoffeeScript" to the console
console.log(check_script("CoffeeScript")); 

31. Tìm số lớn nhất trong ba số nguyên
Viết chương trình JavaScript để xác định số nguyên lớn nhất trong ba giá trị cho trước.

Code mẫu:

// Define a function named max_of_three that takes three parameters: x, y, and z
function max_of_three(x, y, z) {
// Initialize a variable max_val with the value 0
let max_val = 0;

// Check if x is greater than y
if (x > y) {
// If true, assign the value of x to max_val
max_val = x;
} else {
// If false, assign the value of y to max_val
max_val = y;
}

// Check if z is greater than max_val
if (z > max_val) {
// If true, update max_val to the value of z
max_val = z;
}

// Return the final value of max_val
return max_val;
}

// Log the result of calling max_of_three with the arguments 1, 0, 1 to the console
console.log(max_of_three(1, 0, 1));

// Log the result of calling max_of_three with the arguments 0, -10, -20 to the console
console.log(max_of_three(0, -10, -20));

// Log the result of calling max_of_three with the arguments 1000, 510, 440 to the console
console.log(max_of_three(1000, 510, 440)); 

32. Tìm giá trị gần 100 hơn
Viết chương trình JavaScript để so sánh hai số và trả về số nào gần 100 nhất.

Code mẫu:

// Define a function named near_100 with parameters x and y
function near_100(x, y) {
// Check if x is not equal to y
if (x != y) {
// Calculate the absolute difference between x and 100, store it in x1
x1 = Math.abs(x - 100);

// Calculate the absolute difference between y and 100, store it in y1
y1 = Math.abs(y - 100);

// Compare x1 and y1 to determine which value is closer to 100
if (x1 < y1) {
// Return x if x is closer to 100
return x;
}

// Return y if y is closer to 100
if (y1 < x1) {
return y;
}

// Return 0 if x and y are equidistant from 100
return 0;
} else {
// Return false if x is equal to y
return false;
}
}

// Log the result of calling near_100 with the arguments 90 and 89 to the console
console.log(near_100(90, 89));

// Log the result of calling near_100 with the arguments -90 and -89 to the console
console.log(near_100(-90, -89));

// Log the result of calling near_100 with the arguments 90 and 90 to the console
console.log(near_100(90, 90));

33. Kiểm tra hai số trong phạm vi nhất định
Viết chương trình JavaScript để kiểm tra xem cả hai số có cùng nằm trong khoảng 40..60 hoặc 70..100 hay không.

Code mẫu:

// Define a function named numbers_ranges with parameters x and y
function numbers_ranges(x, y) {
// Check if x and y fall within the first range (40 to 60) or the second range (70 to 100)
if ((x >= 40 && x <= 60 && y >= 40 && y <= 60) || (x >= 70 && x <= 100 && y >= 70 && y <= 100)) {
// Return true if the conditions are met
return true;
} else {
// Return false if the conditions are not met
return false;
}
}

// Log the result of calling numbers_ranges with the arguments 44 and 56 to the console
console.log(numbers_ranges(44, 56));

// Log the result of calling numbers_ranges with the arguments 70 and 95 to the console
console.log(numbers_ranges(70, 95));

// Log the result of calling numbers_ranges with the arguments 50 and 89 to the console
console.log(numbers_ranges(50, 89)); 

34. Số lớn hơn trong khoảng 40–60
Viết chương trình JavaScript để tìm số lớn nhất trong hai số nguyên dương nằm trong phạm vi 40 đến 60.

Code mẫu:

// Define a function named max_townums_range with parameters x and y
function max_townums_range(x, y) {
// Check if x and y fall within the specified range using logical AND and comparison operators
if (x >= 40 && x <= 60 && y >= 40 && y <= 60) {
// Check if x and y are the same
if (x === y) {
return "Numbers are the same";
} else if (x > y) {
return x; // Return x if it is greater than y
} else {
return y; // Return y if it is greater than x
}
} else {
return "Numbers don't fit in range"; // Return this message if numbers are outside the range
}
}

// Log the result of calling max_townums_range with the arguments 45 and 60 to the console
console.log(max_townums_range(45, 60));

// Log the result of calling max_townums_range with the arguments 25 and 60 to the console
console.log(max_townums_range(25, 60));

// Log the result of calling max_townums_range with the arguments 45 and 80 to the console
console.log(max_townums_range(45, 80)); 

35. Kiểm tra ký tự trong chuỗi
Viết chương trình JavaScript để xác định xem một ký tự cho trước có nằm trong khoảng từ vị trí thứ 2 đến thứ 4 của chuỗi hay không.

Code mẫu:

// Define a function named check_char with parameters str1 (a string) and char (a character)
function check_char(str1, char)
{
// Initialize a counter variable to 0
let ctr = 0;

// Use a for loop to iterate through each character in the string
for (let i = 0; i < str1.length; i++)
{
// Check if the current character is equal to the specified char and if the index is between 1 and 3 (inclusive)
if ((str1.charAt(i) == char) && (i >= 1 && i <= 3))
{
// Set the counter to 1 and break out of the loop
ctr = 1;
break;
}
}

// Check if the counter is 1 and return true, otherwise return false
if (ctr == 1) return true;
return false;
}

// Log the result of calling check_char with the arguments "Python" and "y" to the console
console.log(check_char("Python", "y"));

// Log the result of calling check_char with the arguments "JavaScript" and "a" to the console
console.log(check_char("JavaScript", "a"));

// Log the result of calling check_char with the arguments "Console" and "o" to the console
console.log(check_char("Console", "o"));

// Log the result of calling check_char with the arguments "Console" and "C" to the console
console.log(check_char("Console", "C"));

// Log the result of calling check_char with the arguments "Console" and "e" to the console
console.log(check_char("Console", "e"));

// Log the result of calling check_char with the arguments "JavaScript" and "S" to the console
console.log(check_char("JavaScript", "S")); 

36. So sánh chữ số cuối cùng
Viết chương trình JavaScript để kiểm tra xem chữ số cuối cùng của ba số nguyên dương có giống nhau không.

Code mẫu:

// Define a function named last_digit with parameters x, y, and z
function last_digit(x, y, z) {
// Check if x, y, and z are greater than 0
if (x > 0 && y > 0 && z > 0) {
// Check if the last digits of x, y, and z are equal
return x % 10 === y % 10 && y % 10 === z % 10 && x % 10 === z % 10;
} else {
// If any of the numbers is not greater than 0, return false
return false;
}
}

// Log the result of calling last_digit with the arguments 20, 30, and 400 to the console
console.log(last_digit(20, 30, 400));

// Log the result of calling last_digit with the arguments -20, 30, and 400 to the console
console.log(last_digit(-20, 30, 400));

// Log the result of calling last_digit with the arguments 20, -30, and 400 to the console
console.log(last_digit(20, -30, 400));

// Log the result of calling last_digit with the arguments 20, 30, and -400 to the console
console.log(last_digit(20, 30, -400)); 

37. Sửa chuỗi theo độ dài
Viết chương trình JavaScript để tạo chuỗi mới: nếu chuỗi ≥ 3 ký tự thì 3 ký tự đầu được viết thường, nếu < 3 ký tự thì viết hoa toàn bộ.

Code mẫu:

// Define a function named upper_lower with parameter str
function upper_lower(str) {
// Check if the length of str is less than 3
if (str.length < 3) {
// If true, return the uppercase version of the entire string
return str.toUpperCase();
} 

// Create a variable named front_part and store the lowercase version of the first 3 characters of str
front_part = (str.substring(0, 3)).toLowerCase(); 

// Create a variable named back_part and store the substring of str from index 3 to the end
back_part = str.substring(3, str.length); 

// Return the concatenation of front_part and back_part
return front_part + back_part;
}

// Log the result of calling upper_lower with the argument "Python" to the console
console.log(upper_lower("Python"));

// Log the result of calling upper_lower with the argument "Py" to the console
console.log(upper_lower("Py"));

// Log the result of calling upper_lower with the argument "JAVAScript" to the console
console.log(upper_lower("JAVAScript")); 

38. Đánh giá điểm số với bài kiểm tra cuối kỳ
Viết chương trình JavaScript để xét điểm học sinh dựa trên tổng điểm và điều kiện bài kiểm tra cuối kỳ.

  • Nếu tổng điểm từ 89–100 → điểm A+.
  • Nếu là bài cuối kỳ → chỉ đạt A+ khi tổng ≥ 90.
  • Chương trình trả về ‘đúng’ nếu đạt A+, ngược lại ‘sai’.

Code mẫu:

// Define a function named exam_status with parameters totmarks and is_exam
function exam_status(totmarks, is_exam) {
// Check if is_exam is truthy (evaluates to true)
if (is_exam) {
// Return true if totmarks is greater than or equal to 90
return totmarks >= 90;
}

// Return true if totmarks is between 89 and 100 (inclusive)
return totmarks >= 89 && totmarks <= 100;
}

// Log the result of calling exam_status with arguments "78" and " " to the console
console.log(exam_status("78", " "));

// Log the result of calling exam_status with arguments "89" and "true " to the console
console.log(exam_status("89", "true "));

// Log the result of calling exam_status with arguments "99" and "true " to the console
console.log(exam_status("99", "true ")); 

39. Tổng hai số nguyên và trả về theo phạm vi
Viết chương trình JavaScript tính tổng của hai số nguyên: nếu tổng trong khoảng 50–80 → trả về 65, ngược lại trả về 80.

Code mẫu:

// Define a function named sortaSum with parameters x and y
function sortaSum(x, y) 
{
// Calculate the sum of x and y and store it in the variable sum_nums
const sum_nums = x + y;

// Check if the sum_nums is between 50 and 80 (inclusive)
if (sum_nums >= 50 && sum_nums <= 80) {
// If true, return 65
return 65;
}

// If the condition is not met, return 80
return 80;
}

// Log the result of calling sortaSum with the arguments 30 and 20 to the console
console.log(sortaSum(30, 20));

// Log the result of calling sortaSum with the arguments 90 and 80 to the console
console.log(sortaSum(90, 80)); 

40. Kiểm tra số 8, tổng hoặc hiệu bằng 8
Viết chương trình JavaScript để xác định xem trong hai số nguyên, có số nào bằng 8 hoặc tổng/hiệu của chúng bằng 8.

Code mẫu:

// Define a function named check8 with parameters x and y
function check8(x, y) {
// Check if x or y is equal to 8
if (x == 8 || y == 8) {
// Return true if the condition is true
return true;
}

// Check if the sum of x and y is equal to 8 or the absolute difference between x and y is equal to 8
if (x + y == 8 || Math.abs(x - y) == 8) {
// Return true if the condition is true
return true;
}

// Return false if none of the conditions are met
return false;
}

// Log the result of calling check8 with the arguments 7 and 8 to the console
console.log(check8(7, 8));

// Log the result of calling check8 with the arguments 16 and 8 to the console
console.log(check8(16, 8));

// Log the result of calling check8 with the arguments 24 and 32 to the console
console.log(check8(24, 32));

// Log the result of calling check8 with the arguments 17 and 18 to the console
console.log(check8(17, 18)); 

41. Trả về 30, 40 hoặc 20 tùy theo số giống nhau
Viết chương trình JavaScript kiểm tra ba số nguyên:

  • Nếu cả ba số giống nhau → trả về 30.
  • Nếu chỉ hai số giống nhau → trả về 40.
  • Nếu không số nào giống nhau → trả về 20.

Code mẫu:

// Define a function named three_numbers using function declaration with parameters x, y, and z
function three_numbers(x, y, z) {
// Check if x, y, and z are equal
if (x == y && y == z) {
return 30;
}

// Check if at least two of x, y, and z are equal
if (x == y || y == z || z == x) {
return 40;
}

// Return 20 if none of the conditions are met
return 20;
}

// Log the result of calling three_numbers with the arguments 8, 8, and 8 to the console
console.log(three_numbers(8, 8, 8));

// Log the result of calling three_numbers with the arguments 8, 8, and 18 to the console
console.log(three_numbers(8, 8, 18));

// Log the result of calling three_numbers with the arguments 8, 7, and 18 to the console
console.log(three_numbers(8, 7, 18)); 

42. Kiểm tra dãy tăng nghiêm ngặt hoặc tăng mềm
Viết chương trình JavaScript để xác định ba số có theo thứ tự tăng:

  • Nghiêm ngặt: ví dụ 10, 15, 31.
  • Mềm: cho phép số đứng trước bằng số sau, ví dụ 22, 22, 31.

Code mẫu:

// Define a function named number_order with parameters x, y, and z
function number_order(x, y, z) {
// Check if y is greater than x and z is greater than y
if (y > x && z > y) {
return "strict mode"; 
} 
// Check if z is greater than y
else if (z > y) {
return "Soft mode";
} 
// If none of the conditions are met, return "Undefined"
else {
return "Undefined";
}
}

// Log the result of calling number_order with the arguments 10, 15, and 31 to the console
console.log(number_order(10, 15, 31));

// Log the result of calling number_order with the arguments 24, 22, and 31 to the console
console.log(number_order(24, 22, 31));

// Log the result of calling number_order with the arguments 50, 21, and 15 to the console
console.log(number_order(50, 21, 15)); 

43. So sánh chữ số cuối của ba số
Viết chương trình JavaScript để kiểm tra trong ba số nguyên không âm, có ít nhất hai số có cùng chữ số tận cùng bên phải hay không.

Code mẫu:

// Define a function named same_last_digit with parameters p, q, and r
function same_last_digit(p, q, r) {
// Return true if the last digit of p is equal to the last digit of q or r,
// or if the last digit of q is equal to the last digit of r
return (p % 10 === q % 10) ||
(p % 10 === r % 10) ||
(q % 10 === r % 10);
}

// Log the result of calling same_last_digit with the arguments 22, 32, and 42 to the console
console.log(same_last_digit(22, 32, 42));

// Log the result of calling same_last_digit with the arguments 102, 302, and 2 to the console
console.log(same_last_digit(102, 302, 2));

// Log the result of calling same_last_digit with the arguments 20, 22, and 45 to the console
console.log(same_last_digit(20, 22, 45)); 

44. Kiểm tra số ≥20 và nhỏ hơn số khác
Viết chương trình JavaScript đánh giá ba số nguyên: xác định có số nào ≥20 và đồng thời nhỏ hơn ít nhất một số khác trong nhóm.

Code mẫu:

// Define a function named lessby20_others with parameters x, y, and z
function lessby20_others(x, y, z) {
// Check if x is greater than or equal to 20 and (x is less than y or x is less than z)
// Check if y is greater than or equal to 20 and (y is less than x or y is less than z)
// Check if z is greater than or equal to 20 and (z is less than y or z is less than x)
return (
(x >= 20 && (x < y || x < z)) ||
(y >= 20 && (y < x || y < z)) ||
(z >= 20 && (z < y || z < x))
);
}

// Log the result of calling lessby20_others with the arguments 23, 45, and 10 to the console
console.log(lessby20_others(23, 45, 10));

// Log the result of calling lessby20_others with the arguments 23, 23, and 10 to the console
console.log(lessby20_others(23, 23, 10));

// Log the result of calling lessby20_others with the arguments 21, 66, and 75 to the console
console.log(lessby20_others(21, 66, 75));

45. Kiểm tra số 15 hoặc tổng/hiệu bằng 15
Viết chương trình JavaScript để kiểm tra hai số nguyên: trả về true nếu một số bằng 15 hoặc tổng/hiệu của chúng bằng 15.

Code mẫu:

// Define a function named test_number with parameters x and y
function test_number(x, y) {
// Return true if x is equal to 15, y is equal to 15, the sum of x and y is equal to 15,
// or the absolute difference between x and y is equal to 15; otherwise, return false.
return (x === 15 || y === 15 || x + y === 15 || Math.abs(x - y) === 15);
}

// Log the result of calling test_number with the arguments 15 and 9 to the console
console.log(test_number(15, 9));

// Log the result of calling test_number with the arguments 25 and 15 to the console
console.log(test_number(25, 15));

// Log the result of calling test_number with the arguments 7 and 8 to the console
console.log(test_number(7, 8));

// Log the result of calling test_number with the arguments 25 and 10 to the console
console.log(test_number(25, 10));

// Log the result of calling test_number with the arguments 5 and 9 to the console
console.log(test_number(5, 9));

// Log the result of calling test_number with the arguments 7 and 9 to the console
console.log(test_number(7, 9));

// Log the result of calling test_number with the arguments 9 and 25 to the console
console.log(test_number(9, 25)); 

46. Một số là bội số của 7 hoặc 11
Viết chương trình JavaScript để xác định trong hai số nguyên không âm, chỉ duy nhất một số (không phải cả hai) là bội số của 7 hoặc 11.

Code mẫu:

// Define a function named valCheck with parameters a and b
function valCheck(a, b) {
// Check if the negation of the condition is true
if (!((a % 7 == 0 || a % 11 == 0) && (b % 7 == 0 || b % 11 == 0))) {
// Return true if either a is divisible by 7 or 11, or b is divisible by 7 or 11
return ((a % 7 == 0 || a % 11 == 0) || (b % 7 == 0 || b % 11 == 0));
} 
else {
// If the negation of the condition is false, return false
return false;
}
}

// Log the result of calling valCheck with the arguments 14 and 21 to the console
console.log(valCheck(14, 21));

// Log the result of calling valCheck with the arguments 14 and 20 to the console
console.log(valCheck(14, 20));

// Log the result of calling valCheck with the arguments 16 and 20 to the console
console.log(valCheck(16, 20)); 

47. Kiểm tra số trong khoảng 40–10.000
Viết chương trình JavaScript để kiểm tra xem một số cho trước có thuộc phạm vi từ 40 đến 10.000 không.
Ví dụ: 40 hợp lệ, 4000 cũng hợp lệ.

Code mẫu:

// Define a function named test_digit with parameter n
function test_digit(n) {
// Check if n is less than 40 or greater than 10000
if (n < 40 || n > 10000)
// Return false if n is outside the specified range
return false;
else
// Check if n is between 40 and 10000 (inclusive)
if (n >= 40 && n <= 10000)
// Return true if n is within the specified range
return true;
}
// Log the result of calling test_digit with the arguments 40 to the console
console.log(test_digit(45));
// Log the result of calling test_digit with the arguments 79 to the console
console.log(test_digit(79));
// Log the result of calling test_digit with the arguments 30 to the console
console.log(test_digit(30));

48. Đảo ngược chuỗi
Viết chương trình JavaScript để nhận một chuỗi đầu vào và trả về chuỗi đảo ngược.

Code mẫu:

// Define a function named string_reverse with a parameter str
function string_reverse(str) {
// Split the string into an array of characters, reverse the order, and join them back into a string
return str.split("").reverse().join("");
}

// Log the result of calling string_reverse with the argument "w3resource" to the console
console.log(string_reverse("w3resource"));

// Log the result of calling string_reverse with the argument "www" to the console
console.log(string_reverse("www"));

// Log the result of calling string_reverse with the argument "JavaScript" to the console
console.log(string_reverse("JavaScript")); 

49. Thay thế ký tự bằng chữ cái kế tiếp
Tạo chương trình JavaScript thay mọi ký tự trong chuỗi thành ký tự tiếp theo trong bảng chữ cái.

Code mẫu:

// Define a function named LetterChanges with parameter text
function LetterChanges(text) {
// Initialize an array by splitting the input text into individual characters
var s = text.split('');

// Iterate through each character in the array
for (var i = 0; i < s.length; i++) {
// Caesar cipher: Shift each character by one position in the alphabet
switch(s[i]) {
case ' ':
break;
case 'z':
s[i] = 'a';
break;
case 'Z': 
s[i] = 'A';
break;
default:
s[i] = String.fromCharCode(1 + s[i].charCodeAt(0));
}

// Convert vowels to uppercase
switch(s[i]) {
case 'a': case 'e': case 'i': case 'o': case 'u':
s[i] = s[i].toUpperCase();
}
}

// Join the modified characters back into a string and return the result
return s.join('');
}

// Log the result of calling LetterChanges with the argument "PYTHON" to the console
console.log(LetterChanges("PYTHON"));

// Log the result of calling LetterChanges with the argument "W3R" to the console
console.log(LetterChanges("W3R"));

// Log the result of calling LetterChanges with the argument "php" to the console
console.log(LetterChanges("php"));

50. Viết hoa chữ cái đầu của mỗi từ
Viết chương trình JavaScript để in hoa ký tự đầu tiên của từng từ trong một chuỗi.

Code mẫu:

// Define a function named capital_letter with parameter str
function capital_letter(str) 
{
// Split the input string into an array of words
str = str.split(" ");

// Iterate through each word in the array
for (var i = 0, x = str.length; i < x; i++) {
// Capitalize the first letter of each word and concatenate it with the rest of the word
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}

// Join the modified array of words back into a string
return str.join(" ");
}

// Log the result of calling capital_letter with the given string to the console
console.log(capital_letter("Write a JavaScript program to capitalize the first letter of each word of a given string.")); 

51. Chuyển số thành giờ và phút
Tạo ứng dụng JavaScript đổi một số cho trước thành định dạng giờ và phút.

Code mẫu:

// Define a function named time_convert with parameter num
function time_convert(num)
{ 
// Calculate the number of hours by dividing num by 60 and rounding down
var hours = Math.floor(num / 60); 

// Calculate the remaining minutes by taking the remainder when dividing num by 60
var minutes = num % 60;

// Return the result as a string in the format "hours:minutes"
return hours + ":" + minutes; 
}

// Log the result of calling time_convert with different numeric inputs to the console
console.log(time_convert(71));
console.log(time_convert(450));
console.log(time_convert(1441)); 

52. Sắp xếp chữ cái trong chuỗi theo alphabet
Viết chương trình JavaScript để sắp xếp các ký tự trong chuỗi theo thứ tự bảng chữ cái.

Code mẫu:

// Define a function named alphabet_Soup with parameter str
function alphabet_Soup(str) { 
// Split the string into an array of characters, sort the array, and join it back into a string
return str.split("").sort().join("");
}

// Log the result of calling alphabet_Soup with the given strings to the console
console.log(alphabet_Soup("Python"));
console.log(alphabet_Soup("Exercises")); 

53. Kiểm tra ‘a’ và ‘b’ cách nhau 3 ký tự
Viết chương trình JavaScript kiểm tra xem trong chuỗi có cặp ký tự ‘a’ và ‘b’ cách nhau đúng 3 vị trí hay không.

Code mẫu:

// Define a function named ab_Check with parameter str
function ab_Check(str) {
// Use regular expressions to check if the pattern 'a...b' or 'b...a' exists in the given string
// The test() method returns true if the pattern is found, otherwise, it returns false
return (/a...b/).test(str) || (/b...a/).test(str);
}

// Log the result of calling ab_Check with the given strings to the console
console.log(ab_Check("Chainsbreak"));
console.log(ab_Check("pane borrowed"));
console.log(ab_Check("abCheck")); 

54. Đếm nguyên âm trong chuỗi
Viết chương trình JavaScript để đếm số lượng nguyên âm có trong một chuỗi cho trước.

Code mẫu:

// Define a function named vowel_Count with parameter str
function vowel_Count(str) {
// Use regular expression to replace all characters not in 'aeiou' with an empty string
// and get the length of the resulting string, which is the count of vowels
return str.replace(/[^aeiou]/g, "").length;
}

// Log the result of calling vowel_Count with the given strings to the console
console.log(vowel_Count("Python"));
console.log(vowel_Count("w3resource.com")); 

55. So sánh số lượng ký tự ‘p’ và ‘t’
Tạo chương trình JavaScript để kiểm tra xem chuỗi có chứa số lượng chữ ‘p’ và chữ ‘t’ bằng nhau không.

Code mẫu:

// Define a function named equal_pt with parameter str
function equal_pt(str) { 
// Replace all characters except 'p' with an empty string and store the result in str_p
var str_p = str.replace(/[^p]/g, "");

// Replace all characters except 't' with an empty string and store the result in str_t
var str_t = str.replace(/[^t]/g, "");

// Get the length of str_p and store it in p_num
var p_num = str_p.length;

// Get the length of str_t and store it in s_num
var s_num = str_t.length;

// Return true if the lengths of str_p and str_t are equal; otherwise, return false
return p_num === s_num;
}

// Log the result of calling equal_pt with the given strings to the console
console.log(equal_pt("paatpss"));
console.log(equal_pt("paatps"));

56. Chia số và định dạng dấu phẩy
Viết chương trình JavaScript chia hai số dương, sau đó trả về kết quả dưới dạng chuỗi có dấu phẩy phân tách.

Code mẫu:

// Function to divide two numbers and format the result with commas
function division_string_format(number1, number2) {
// Check if the divisor is zero
if (number2 === 0) {
return "Cannot divide by zero";
}
// Perform division
let result = number1 / number2;
// Format result with commas
let formattedResult = result.toLocaleString(undefined, {maximumFractionDigits: 2});
// Return the formatted result
return formattedResult;
}
// Example usage:
// Define the dividend and divisor
let dividend = 1000000;
let divisor = 107;
// Perform division and format the result
let result = division_string_format(dividend, divisor);
// Print the result
console.log("Result: " + result);

57. Tạo chuỗi lặp lại nhiều lần
Viết chương trình JavaScript để tạo một chuỗi mới bằng cách nhân bản chuỗi gốc số lần cho trước.

Code mẫu:

// Define a function named string_copies with parameters str (string) and n (number)
function string_copies(str, n) {
// Check if n is less than 0
if (n < 0)
// Return false if n is negative
return false;
else
// Use the repeat method to replicate the string 'n' times
return str.repeat(n);
}

// Log the result of calling string_copies with the arguments "abc" and 5 to the console
console.log(string_copies("abc", 5));
// Log the result of calling string_copies with the arguments "abc" and 0 to the console
console.log(string_copies("abc", 0));
// Log the result of calling string_copies with the arguments "abc" and -2 to the console
console.log(string_copies("abc", -2)); 

58. Bốn lần lặp lại 3 ký tự cuối
Tạo chương trình JavaScript sinh ra chuỗi mới gồm 4 bản sao của 3 ký tự cuối chuỗi gốc (chuỗi phải dài ≥3).

Code mẫu:

// Define a function named newstring with parameter str
function newstring(str) {
// Check if the length of str is greater than or equal to 3
if (str.length >= 3) {
// Extract the last 3 characters of str
result_str = str.substring(str.length - 3);
// Return a new string containing the last 3 characters repeated four times
return result_str + result_str + result_str + result_str;
} else {
// Return false if the length of str is less than 3
return false;
}
}

// Call the function with sample arguments and log the results to the console
console.log(newstring("Python 3.0"));
console.log(newstring("JS"));
console.log(newstring("JavaScript")); 

59. Lấy nửa đầu của chuỗi có độ dài chẵn
Viết chương trình JavaScript để trích xuất nửa đầu từ một chuỗi có số ký tự chẵn.

Code mẫu:

// Define a function named first_half with parameter str
function first_half(str) {
// Check if the length of the string is even
if (str.length % 2 == 0) {
// Use the slice method to get the first half of the string
return str.slice(0, str.length / 2);
}
// If the length is odd, return the original string
return str;
}

// Call the function with sample arguments and log the results to the console
console.log(first_half("Python")); // Outputs "Py"
console.log(first_half("JavaScript")); // Outputs "Java"
console.log(first_half("PHP")); // Outputs "PHP" 

60. Loại bỏ ký tự đầu và cuối chuỗi
Tạo chương trình JavaScript để trả về chuỗi mới không chứa ký tự đầu tiên và cuối cùng.

Code mẫu:

// Define a function named without_first_end with parameter str
function without_first_end(str) {
// Use substring to get a portion of the string excluding the first and last characters
return str.substring(1, str.length - 1);
}

// Call the function with sample arguments and log the results to the console
console.log(without_first_end('JavaScript'));
console.log(without_first_end('JS'));
console.log(without_first_end('PHP')); 

61. Ghép hai chuỗi bỏ ký tự đầu
Viết chương trình JavaScript nối hai chuỗi nhưng bỏ qua ký tự đầu tiên của mỗi chuỗi.

Code mẫu:

// Define a function named concatenate with parameters str1 and str2
function concatenate(str1, str2) {
// Modify str1 to exclude the first character
str1 = str1.substring(1, str1.length);
// Modify str2 to exclude the first character
str2 = str2.substring(1, str2.length);
// Return the concatenation of modified str1 and str2
return str1 + str2;
}


// Call the function with sample arguments and log the results to the console
console.log(concatenate("PHP", "JS"));
console.log(concatenate("A", "B"));
console.log(concatenate("AA", "BB"));

62. Đưa 3 ký tự cuối lên đầu chuỗi
Viết chương trình JavaScript dịch chuyển 3 ký tự cuối cùng của chuỗi lên đầu (chuỗi phải dài ≥3).

Code mẫu:

// Define a function named right_three with parameter str
function right_three(str) {
// Check if the length of the string is greater than 1
if (str.length > 1) {
// Return the last three characters concatenated with the substring excluding the last three characters
return str.slice(-3) + str.slice(0, -3);
}
// Return the string as is if its length is not greater than 1
return str;
}

// Call the function with sample arguments and log the results to the console
console.log(right_three("Python"));
console.log(right_three("JavaScript"));
console.log(right_three("Hi")); 

63. Trích xuất 3 ký tự giữa của chuỗi lẻ
Tạo chương trình JavaScript lấy ra 3 ký tự chính giữa từ chuỗi có độ dài lẻ (≥3).

Code mẫu:

// Define a function named middle_three with parameter str
function middle_three(str) {
// Check if the length of str is odd
if (str.length % 2 !== 0) {
// Calculate the middle index for odd-length strings
mid = (str.length + 1) / 2;
// Use slice to get the middle three characters and return
return str.slice(mid - 2, mid + 1);
}
// Return str if its length is not odd
return str;
}

// Call the function with sample arguments and log the results to the console
console.log(middle_three('abcdefg'));
console.log(middle_three('HTML5'));
console.log(middle_three('Python'));
console.log(middle_three('PHP'));
console.log(middle_three('Exercises')); 

64. Nối chuỗi có độ dài tương ứng
Viết chương trình JavaScript nối hai chuỗi, nếu độ dài không bằng nhau thì cắt bớt chuỗi dài hơn.

Code mẫu:

// Define a function named str_con_cat with parameters str1 and str2
function str_con_cat(str1, str2) {
// Calculate the minimum length of str1 and str2
const m = Math.min(str1.length, str2.length); 
// Use substring to concatenate the common characters from the end of both strings
return str1.substring(str1.length - m) + str2.substring(str2.length - m);
}

// Call the function with sample arguments and log the results to the console
console.log(str_con_cat("Python", "JS"));
console.log(str_con_cat("ab", "cdef")); 

65. Kiểm tra chuỗi kết thúc bằng “Script”
Viết chương trình JavaScript để xác định chuỗi có kết thúc bằng “Script” hay không (chuỗi ≥6 ký tự).

Code mẫu:

// Define a function named end_script with parameter str
function end_script(str) {
// Check if the last 6 characters of str are equal to 'Script'
if (str.substring(str.length - 6, str.length) == 'Script') {
// Return true if the condition is met
return true;
} else {
// Return false if the condition is not met
return false;
}
}

// Call the function with sample arguments and log the results to the console
console.log(end_script("JavaScript"));
console.log(end_script("Java Script"));
console.log(end_script("Java Scripts"));

66. Trả về tên thành phố bắt đầu bằng “Los” hoặc “New”
Viết chương trình JavaScript để hiển thị tên thành phố nếu chuỗi bắt đầu bằng “Los” hoặc “New”. Nếu không, trả về rỗng.

Code mẫu:

// Define a function named city_name with parameter str
function city_name(str) {
// Check if str has length greater than or equal to 3 and starts with 'Los' or 'New'
if (str.length >= 3 && ((str.substring(0, 3) == 'Los') || (str.substring(0, 3) == 'New'))) {
// Return the input str if conditions are met
return str;
}

// Return an empty string if conditions are not met
return '';
}

// Call the function with sample arguments and log the results to the console
console.log(city_name("New York"));
console.log(city_name("Los Angeles"));
console.log(city_name("London")); 

67. Xóa ký tự ‘P’ ở đầu/cuối chuỗi
Tạo chương trình JavaScript để loại bỏ ký tự ‘P’ nếu nó xuất hiện ở đầu hoặc cuối chuỗi. Nếu không, trả về chuỗi ban đầu.

Code mẫu:

// Define a function named nop with parameter str
function nop(str) {
// Initialize start_pos variable to 0
let start_pos = 0;
// Initialize end_pos variable to the length of the input string
let end_pos = str.length;

// Check if the string has a length greater than 0 and the first character is 'P'
if (str.length > 0 && str.charAt(0) == 'P') { 
// If true, set start_pos to 1
start_pos = 1; 
}

// Check if the string has a length greater than 1 and the last character is 'P'
if (str.length > 1 && str.charAt(str.length - 1) == 'P') {
// If true, decrement end_pos by 1
end_pos--;
}

// Return a substring of the input string from start_pos to end_pos
return str.substring(start_pos, end_pos);
}

// Call the function with sample arguments and log the results to the console
console.log(nop("PythonP"));
console.log(nop("Python"));
console.log(nop("JavaScript")); 

68. Tạo chuỗi từ n ký tự đầu và cuối
Viết chương trình JavaScript để tạo chuỗi mới gồm n ký tự đầu tiên và n ký tự cuối cùng (chuỗi ≥ n).

Code mẫu:

// Define a function named two_string with parameters str and n
function two_string(str, n) {
// Extract the first part of the string from index 0 to n (exclusive)
first_part = str.substring(0, n);
// Extract the last part of the string from (length - n) to the end
last_part = str.substring(str.length - n);
// Concatenate the first and last parts and return the result
return first_part + last_part;
}

// Call the function with sample arguments and log the results to the console
console.log(two_string("JavaScript", 2));
console.log(two_string("JavaScript", 3));

69. Tổng của 3 phần tử trong mảng
Viết chương trình JavaScript tính tổng 3 phần tử của một mảng số nguyên có độ dài 3.

Code mẫu:

// Define a function named sum_three that takes an array of three numbers as a parameter
function sum_three(nums) {
// Return the sum of the three numbers using array indexing
return nums[0] + nums[1] + nums[2];
}

// Call the function with different arrays and log the results to the console
console.log(sum_three([10, 32, 20]));
console.log(sum_three([5, 7, 9]));
console.log(sum_three([0, 8, -11]));

70. Xoay trái các phần tử mảng (3 phần tử)
Tạo chương trình JavaScript để xoay trái mảng số nguyên có độ dài 3.

Code mẫu:

// Define a function named rotate_elements_left with a parameter array
function rotate_elements_left(array)
{
// Return a new array with elements rotated to the left
// The new order is [array[1], array[2], array[0]]
return [array[1], array[2], array[0]];
}

// Call the function with sample arguments and log the results to the console
console.log(rotate_elements_left([3, 4, 5]));
console.log(rotate_elements_left([0, -1, 2]));
console.log(rotate_elements_left([7, 6, 5])); 

71. Kiểm tra số 1 ở đầu hoặc cuối mảng
Viết chương trình JavaScript để kiểm tra xem số 1 có xuất hiện ở vị trí đầu tiên hoặc cuối cùng trong mảng không (mảng ≥1 phần tử).

Code mẫu:

// Define a function named first_last_1 with a parameter nums
function first_last_1(nums)
{
// Calculate the index of the last element in the array
var end_pos = nums.length - 1;
// Check if the first or last element in the array is equal to 1, and return the result
return nums[0] == 1 || nums[end_pos] == 1;
}

// Call the function with sample arguments and log the results to the console
console.log(first_last_1([1, 3, 5]));
console.log(first_last_1([1, 3, 5, 1]));
console.log(first_last_1([2, 4, 6]));

72. So sánh phần tử đầu và cuối mảng
Tạo chương trình JavaScript để kiểm tra xem phần tử đầu tiên và cuối cùng của mảng có giống nhau không (mảng dài 3).

Code mẫu:

// Define a function named first_last_same with a parameter nums
function first_last_same(nums) {
// Calculate the index of the last element in the array
var end = nums.length - 1;

// Check if the array has at least one element
if (nums.length >= 1) {
// Return true if the first and last elements of the array are equal, otherwise return false
return nums[0] == nums[end];
} else {
// Return false if the array is empty
return false;
}
}

// Call the function with sample arguments and log the results to the console
console.log(first_last_same([10, 20, 30])); 
console.log(first_last_same([10, 20, 30, 10])); 
console.log(first_last_same([20, 20, 20])); 

73. Đảo ngược mảng 3 phần tử
Viết chương trình JavaScript để đảo ngược thứ tự các phần tử trong mảng có độ dài 3.

Code mẫu:

// Define a function named reverse3 that takes an array as a parameter
function reverse3(array) {
// Use the map method to iterate over the array and reverse the order
return array.map((element, idx, arr) => arr[(arr.length - 1) - idx]);
}

// Call the function with sample arguments and log the results to the console
console.log(reverse3([5, 4, 3])); // Output: [3, 4, 5]
console.log(reverse3([1, 0, -1])); // Output: [-1, 0, 1]
console.log(reverse3([2, 3, 1])); // Output: [1, 3, 2] 

74. Gán tất cả phần tử bằng giá trị lớn nhất (giữa đầu/cuối)
Viết chương trình JavaScript để so sánh phần tử đầu và cuối của mảng, lấy giá trị lớn hơn và gán cho toàn bộ phần tử.

Code mẫu:

// Define a function named all_max that takes an array of numbers as a parameter
function all_max(nums) 
{
// Determine the maximum value between the first and third elements using a ternary operator
var max_val = nums[0] > nums[2] ? nums[0] : nums[2];

// Set all elements in the array to the determined maximum value
nums[0] = max_val;
nums[1] = max_val;
nums[2] = max_val;

// Return the modified array
return nums;
}

// Call the function with sample arguments and log the results to the console
console.log(all_max([20, 30, 40])); // Output: [40, 40, 40]
console.log(all_max([-7, -9, 0])); // Output: [0, 0, 0]
console.log(all_max([12, 10, 3])); // Output: [12, 12, 12] 

75. Tạo mảng từ phần tử giữa của hai mảng
Viết chương trình JavaScript tạo mảng mới từ phần tử giữa của hai mảng số nguyên (mỗi mảng dài 3).

Code mẫu:

// Define a function named middle_elements that takes two arrays, 'a' and 'b', as parameters
function middle_elements(a, b) {
// Create a new array named 'new_array'
var new_array = [];

// Push the second elements of both arrays into the new_array
new_array.push(a[1], b[1]);

// Return the new_array
return new_array;
}

// Call the function with sample arguments and log the results to the console
console.log(middle_elements([1, 2, 3], [1, 5, 6])); // Output: [2, 5]
console.log(middle_elements([3, 3, 3], [2, 8, 0])); // Output: [3, 8]
console.log(middle_elements([4, 2, 7], [2, 4, 5])); // Output: [2, 4] 

76. Tạo mảng từ phần tử đầu và cuối
Viết chương trình JavaScript để trả về mảng gồm phần tử đầu tiên và cuối cùng của một mảng cho trước (mảng ≥1).

Code mẫu:

// Function that returns an array containing the first and last elements of the input array
function started(nums) {
var array1 = []; // Create an empty array to store the first and last elements
array1.push(nums[0], nums[nums.length - 1]); // Add the first and last elements to the array
return array1; // Return the array with the first and last elements
}
// Example usage of the started function with different input arrays
console.log(started([20, 20, 30])); // Output: [20, 30]
console.log(started([5, 2, 7, 8])); // Output: [5, 8]
console.log(started([17, 12, 34, 78])); // Output: [17, 78]

77. Kiểm tra mảng có chứa 1 hay 3
Viết chương trình JavaScript để kiểm tra mảng (dài 2) có chứa số 1 hoặc số 3 hay không.

Code mẫu:

// Function checks if the array 'nums' contains either 1 or 3
function contains13(nums) {
// Check if 1 is present at any index or 3 is present at any index
if (nums.indexOf(1) !== -1 || nums.indexOf(3) !== -1) {
// Return true if either 1 or 3 is found
return true;
} else {
// Return false if neither 1 nor 3 is found
return false;
}
}

// Example usage of the contains13 function
console.log(contains13([1, 5])); // Should return true, as 1 is present
console.log(contains13([2, 3])); // Should return true, as 3 is present
console.log(contains13([7, 5])); // Should return false, as neither 1 nor 3 is present 

78. Kiểm tra mảng có chứa 1 hoặc 3
Tạo chương trình JavaScript để kiểm tra mảng dài 2 có phần tử bằng 1 hoặc 3.

Code mẫu:

// Function checks if the array does not contain the values 1 or 3
function is13(nums) {
// Check if index of 1 is -1 (not found) and index of 3 is -1 (not found)
if (nums.indexOf(1) == -1 && nums.indexOf(3) == -1) {
// If both values are not found, return true
return true;
} else {
// If at least one of the values is found, return false
return false;
}
}

// Example usage
console.log(is13([7, 8])); // true, as neither 1 nor 3 is present
console.log(is13([3, 2])); // false, as 3 is present
console.log(is13([0, 1])); // false, as 1 is present

79. Kiểm tra mảng chứa hai lần 30 và 40
Viết chương trình JavaScript để kiểm tra mảng số nguyên (dài ≤2) có chứa cả 30 và 40, mỗi số xuất hiện đúng 2 lần.

Code mẫu:

// Function to check if the first two elements of an array are either both 30 or both 40
function twice3040(arra1) {
let a = arra1[0], // Extract the first element
b = arra1[1]; // Extract the second element
return (a === 30 && b === 30) || (a === 40 && b === 40); // Check if both are 30 or both are 40
} 

// Example usage
console.log(twice3040([30, 30])); // Should return true
console.log(twice3040([40, 40])); // Should return true
console.log(twice3040([20, 20])); // Should return false
console.log(twice3040([30])); // Should return false

80. Hoán đổi phần tử đầu và cuối mảng
Tạo chương trình JavaScript để đổi chỗ phần tử đầu và cuối của mảng (mảng ≥1).

Code mẫu:

// Function to swap the first and last elements of an array
function swap(arra) {
// Destructuring assignment to swap values without using a temporary variable
[arra[0], arra[arra.length - 1]] = [arra[arra.length - 1], arra[0]];
// Return the modified array
return arra;
}

// Example usage
console.log(swap([1, 2, 3, 4]));
console.log(swap([0, 2, 1]));
console.log(swap([3])); 

81. Cộng hai chữ số trong số có hai chữ số
Viết chương trình JavaScript để tính tổng của hai chữ số từ số nguyên dương có 2 chữ số.

Code mẫu:

// Function to add the two digits of a number
function add_two_digits(n) {
// Return the sum of the last digit and the result of dividing the number by 10 and rounding down
return n % 10 + Math.floor(n / 10);
} 

// Example usage
console.log(add_two_digits(25)); // Output: 7 (2 + 5)
console.log(add_two_digits(50)); // Output: 5 (5 + 0)

82. Cộng hai số nguyên không nhớ
Tạo chương trình JavaScript để cộng hai số nguyên dương mà không thực hiện phép nhớ.

Code mẫu:

// Function to add two integers without carrying
function add_two_int_without_carrying(n1, n2) {
var result = 0, // Initialize the result
x = 1; // Initialize the multiplier

// Iterate while both numbers have digits
while (n1 > 0 && n2 > 0) {
result += x * ((n1 + n2) % 10); // Add the current digit without carrying
n1 = Math.floor(n1 / 10); // Move to the next digit in the first number
n2 = Math.floor(n2 / 10); // Move to the next digit in the second number
x *= 10; // Update the multiplier for the next digit place
}

return result; // Return the final result
}

// Example usage
console.log(add_two_int_without_carrying(222, 911)); // Output: 133
console.log(add_two_int_without_carrying(200, 900)); // Output: 100

83. Tìm chuỗi dài nhất trong mảng
Viết chương trình JavaScript để tìm phần tử có độ dài lớn nhất trong một mảng chuỗi.

Code mẫu:

// Function to find the longest string(s) in an array
function longest_string(str_ara) {
var max = str_ara[0].length; // Initialize max length with the length of the first string
str_ara.map(v => max = Math.max(max, v.length)); // Update max with the maximum length in the array using the map function
result = str_ara.filter(v => v.length == max); // Filter out strings that have the maximum length
return result; // Return the array of longest strings
} 

// Example usage
console.log(longest_string(['a', 'aa', 'aaa', 'aaaaa', 'aaaa'])); 

84. Thay thế ký tự bằng chữ cái kế tiếp (a→b, z→a)
Viết chương trình JavaScript thay mỗi ký tự trong chuỗi bằng chữ cái tiếp theo trong bảng chữ cái.

Code mẫu:

// Function to shift each alphabet character in the input string to the next character in the alphabet
function alphabet_char_Shift(str) {
var all_chars = str.split(""); // Convert the input string into an array of characters
for(var i = 0; i < all_chars.length; i++) { // Iterate over each character in the array
var n = all_chars[i].charCodeAt() - 'a'.charCodeAt(); // Calculate the position of the character in the alphabet
n = (n + 1) % 26; // Shift the position to the next character in the alphabet, considering circular nature
all_chars[i] = String.fromCharCode(n + 'a'.charCodeAt()); // Update the character with the shifted character
}
return all_chars.join(""); // Convert the array of characters back to a string and return
}

// Example usage
console.log(alphabet_char_Shift("abcdxyz"));

85. Tách mảng thành hai nhóm xen kẽ và tính tổng
Viết chương trình JavaScript chia một mảng thành hai nhóm xen kẽ, tính tổng từng nhóm rồi trả về mảng gồm 2 phần tử.

Code mẫu:

// Function to calculate alternate sums of elements in an array
function alternate_Sums(arr) {
var result = [0, 0]; // Initialize an array to store alternate sums
for(var i = 0; i < arr.length; i++) 
{ 
if(i % 2) result[1] += arr[i]; // If index is odd, add the element to the second sum
else
result[0] += arr[i]; // If index is even, add the element to the first sum
}
return result; // Return the array of alternate sums
}

// Example usage
console.log(alternate_Sums([1, 3, 6, 2, 5, 10])); // Output: [14, 8]

86. Xác định loại góc
Viết chương trình JavaScript phân loại góc theo số đo:

  • Nhọn: 0–90°
  • Vuông: 90°
  • Tù: 90–180°
  • Thẳng: 180°

Code mẫu:

 // Function to determine the type of angle based on its measure
function angle_Type(angle) {
if(angle < 90) {
return "Acute angle."; // Return this message if the angle is less than 90 degrees
}
if(angle === 90) {
return "Right angle."; // Return this message if the angle is exactly 90 degrees
}
if(angle < 180) {
return "Obtuse angle."; // Return this message if the angle is less than 180 degrees but not 90 degrees
}
return "Straight angle."; // Return this message if the angle is exactly 180 degrees
}

// Example usage
console.log(angle_Type(47)); // Acute angle.
console.log(angle_Type(90)); // Right angle.
console.log(angle_Type(145)); // Obtuse angle.
console.log(angle_Type(180)); // Straight angle.

87. Kiểm tra hai mảng đồng dạng bằng một phép hoán đổi
Viết chương trình JavaScript để xem hai mảng số nguyên có cùng độ dài có thể giống nhau nếu hoán đổi tối đa một cặp phần tử hay không.

Code mẫu:

// Function to check if rearranging elements of one array can make it equal to another array
function array_checking(arra1, arra2) {
// Iterate through elements of arra1
for (var i = 0; i < arra1.length; i++) {
// Nested loop to swap elements and check permutations
for (var j = i; j < arra1.length; j++) {
// Initialize result and temporary variable
var result = true,
temp = arra1[i];

// Swap elements
arra1[i] = arra1[j];
arra1[j] = temp;

// Compare elements of the modified arra1 with arra2
for (var k = 0; k < arra1.length; k++) {
if (arra1[k] !== arra2[k]) {
result = false;
break;
}
}

// If the arrays match, return true
if (result) {
return true;
}

// Restore the original order by swapping back elements
arra1[j] = arra1[i];
arra1[i] = temp;
}
}

// If no match is found, return false
return false;
}

// Example usage
console.log(array_checking([10, 20, 30], [10, 20, 30])); // true
console.log(array_checking([10, 20, 30], [30, 10, 20])); // true
console.log(array_checking([10, 20, 30, 40], [10, 30, 20, 40])); // false

88. Kiểm tra đồng dạng của hai số nguyên với ước số
Viết chương trình JavaScript để xác định hai số nguyên có đồng dạng hay không, dựa trên một ước số cho trước chia hết cả hai hoặc không chia hết số nào.

Code mẫu:

// Function to check if two numbers are both divisible or not divisible by a given divisor
function checking_numbers(x, y, divisor) {
// Check if both x and y are divisible by the divisor or not divisible by the divisor
if (x % divisor === 0 && y % divisor === 0 || x % divisor !== 0 && y % divisor !== 0) {
return true; // Return true if the condition is satisfied
}
return false; // Return false if the condition is not satisfied
}

// Example usage
console.log(checking_numbers(10, 25, 5)); // true
console.log(checking_numbers(10, 20, 5)); // true
console.log(checking_numbers(10, 20, 4)); // false 

89. Thay thế ký hiệu $ để biểu thức đúng
Viết chương trình JavaScript để kiểm tra xem có thể thay $ trong biểu thức x $ y = z bằng +, -, * hoặc / để biểu thức đúng không.

Code mẫu:

// Function to check if two numbers are both divisible or not divisible by a given divisor
function checking_numbers(x, y, divisor) {
// Check if both x and y are divisible by the divisor or not divisible by the divisor
if (x % divisor === 0 && y % divisor === 0 || x % divisor !== 0 && y % divisor !== 0) {
return true; // Return true if the condition is satisfied
}
return false; // Return false if the condition is not satisfied
}

// Example usage
console.log(checking_numbers(10, 25, 5)); // true
console.log(checking_numbers(10, 20, 5)); // true
console.log(checking_numbers(10, 20, 4)); // false 

90. Phần tử lớn thứ k trong mảng
Viết chương trình JavaScript tìm phần tử lớn thứ k trong mảng số nguyên.

Code mẫu:

// Function to find the Kth greatest element in an array
function Kth_greatest_in_array(arr, k) {
// Iterate for the first K elements
for (var i = 0; i < k; i++) {
var max_index = i, // Assume the current index as the maximum index
tmp = arr[i]; // Temporary variable to store the current element 
// Iterate through the remaining elements to find the maximum
for (var j = i + 1; j < arr.length; j++) {
// If the current element is greater than the element at max_index, update max_index
if (arr[j] > arr[max_index]) {
max_index = j;
}
}

// Swap the current element with the maximum element found
arr[i] = arr[max_index];
arr[max_index] = tmp;
}

// Return the Kth greatest element
return arr[k - 1];
}

// Example usage
console.log(Kth_greatest_in_array([1,2,6,4,5], 3)); // 4
console.log(Kth_greatest_in_array([-10,-25,-47,-36,0], 1)); // 0

91. Tổng lớn nhất của k phần tử liên tiếp
Tìm tổng lớn nhất của bất kỳ dãy k phần tử kề nhau trong mảng số nguyên dương.

Code mẫu:

function array_max_consecutive_sum(nums, k) {
let result = 0;
let temp_sum = 0;
for (var i = 0; i < k - 1; i++) {
temp_sum += nums[i];
}
for (var i = k - 1; i < nums.length; i++) {
temp_sum += nums[i];
if (temp_sum > result) {
result = temp_sum;
}
temp_sum -= nums[i - k + 1];
}
return result;
}

console.log(array_max_consecutive_sum([1, 2, 3, 14, 5], 2))
console.log(array_max_consecutive_sum([2, 3, 5, 1, 6], 3))
console.log(array_max_consecutive_sum([9, 3, 5, 1, 7], 2))

92. Hiệu lớn nhất giữa hai phần tử liền kề
Xác định khoảng chênh lệch lớn nhất giữa các cặp phần tử kề nhau trong mảng.

Code mẫu:

// Function to find the maximum difference between adjacent elements in an array
function max_difference(arr) {
var max = -1; // Initialize a variable to store the maximum difference
var temp; // Temporary variable to calculate the difference

// Iterate through the array to find the maximum difference
for (var i = 0; i < arr.length - 1; i++) {
temp = Math.abs(arr[i] - arr[i + 1]); // Calculate the absolute difference
max = Math.max(max, temp); // Update the maximum difference
}

return max; // Return the final maximum difference
}

// Example usage
console.log(max_difference([1, 2, 3, 8, 9])); // 5
console.log(max_difference([1, 2, 3, 18, 9])); // 15
console.log(max_difference([13, 2, 3, 8, 9])); // 11 

93. Hiệu lớn nhất giữa mọi cặp phần tử
Tìm hiệu số lớn nhất có thể giữa hai phần tử bất kỳ trong mảng.

Code mẫu:

// Function to find the maximum difference between any two elements in an array
function array_max_diff(arr) {
var max_result = 0; // Initialize the variable to store the maximum difference

// Iterate through the array elements
for(var i = 0; i < arr.length; i++) {
// Iterate through other elements in the array
for(var k = 0; k !== i && k < arr.length; k++) {
var diff = Math.abs(arr[i] - arr[k]); // Calculate the absolute difference
max_result = Math.max(max_result, diff); // Update the maximum difference
}
} 

return max_result; // Return the final maximum difference
}

// Example usage
console.log(array_max_diff([1, 2, 3, 8, 9])); // 8
console.log(array_max_diff([1, 2, 3, 18, 9])); // 17
console.log(array_max_diff([13, 2, 3, 8, 9])); // 11 

94. Phần tử xuất hiện nhiều nhất
Xác định giá trị xuất hiện với tần suất cao nhất trong mảng số nguyên.

Code mẫu:

// Function to find the mode (most frequently occurring element) in an array
function array_element_mode(arr) {
var ctr = [], // Counter array to store frequencies of elements
ans = 0; // Variable to store the index of the mode

// Initialize the counter array with zeros for each possible element
for (var i = 0; i < 10; i++) {
ctr.push(0);
}

// Iterate through the input array to update the frequencies in the counter array
for (var i = 0; i < arr.length; i++) {
ctr[arr[i] - 1]++; // Increment the frequency of the current element
if (ctr[arr[i] - 1] > ctr[ans]) {
ans = arr[i] - 1; // Update the index of the mode if a higher frequency is found
}
}

return ans + 1; // Return the mode (add 1 to convert from zero-based index to element value)
}

// Example usage
console.log(array_element_mode([1, 2, 3, 2, 2, 8, 1, 9])); // 2

95. Thay toàn bộ số bằng một giá trị chỉ định
Thay tất cả phần tử số trong mảng bằng một số cho trước.

Code mẫu:

// Function to replace a specified element in an array with a new value
function array_element_replace(arr, old_value, new_value) {
for (var i = 0; i < arr.length; i++) {
// Check if the current element is equal to the old value
if (arr[i] === old_value) {
arr[i] = new_value; // Replace the old value with the new value
}
}
return arr; // Return the modified array
}

// Example usage
num = [1, 2, 3, 2, 2, 8, 1, 9]; // Original array
console.log("Original Array: " + num);
console.log(array_element_replace(num, 2, 5)); // Replace 2 with 5 in the array

96. Tổng các hiệu tuyệt đối liên tiếp
Tính tổng |a[i] − a[i−1]| cho toàn bộ mảng số nguyên.

Code mẫu:

// Function to calculate the sum of adjacent differences in an array
function sum_adjacent_difference(arr) {
var result = 0; // Variable to store the result
for (var i = 1; i < arr.length; i++) {
// Add the absolute difference between adjacent elements to the result
result += Math.abs(arr[i] - arr[i - 1]);
}
return result; // Return the final sum
}

console.log(sum_adjacent_difference([1, 2, 3, 2, -5])); // Example usage

97. Chuỗi ngắn nhất có thể thành palindrome (thêm ở cuối)
Tìm chuỗi ngắn nhất để khi thêm vào cuối chuỗi gốc sẽ biến nó thành palindrome.

Code mẫu:

// Function to build a palindrome from a given string
function build_Palindrome(new_str) {
var flag; // Variable to check if a palindrome is found
for (var i = new_str.length;; i++) { // Loop to increment the length for building a palindrome
flag = true; // Set the flag initially to true for each iteration
for (var j = 0; j < i - j - 1; j++) { // Loop to check for palindrome condition
// Check if characters symmetrically positioned around the center are equal
if (i - j - 1 < new_str.length && new_str[j] != new_str[i - j - 1]) {
flag = false; // Set flag to false if characters are not equal
break; // Break the loop if not a palindrome
} 
}
if (flag) {
// If a palindrome is found, complete the palindrome by adding the remaining characters
for (var j = new_str.length; j < i; j++) {
new_str += new_str[i - j - 1];
}
return new_str; // Return the palindrome
}
}
}

console.log(build_Palindrome("abcddc")); // Output the result for the given string
console.log(build_Palindrome("122")); // Output the result for the given string

98. Đổi ít ký tự nhất để toàn chuỗi viết hoa/thường
Biến chuỗi thành toàn chữ hoa hoặc toàn chữ thường với số ký tự thay đổi tối thiểu.

Code mẫu:

// Function to change case based on the character count of upper and lower case letters
function change_case(new_str) {
var x = 0; // Variable to count the number of uppercase letters
var y = 0; // Variable to count the number of lowercase letters
// Loop through each character in the input string
for (var i = 0; i < new_str.length; i++) {
// Check if the current character is an uppercase letter using a regular expression
if (/[A-Z]/.test(new_str[i])) {
x++; // Increment the count of uppercase letters
} else {
y++; // Increment the count of lowercase letters
}
}

// Compare the counts and change the case of the input string accordingly
if (y > x) {
return new_str.toLowerCase(); // If lowercase count is greater, return string in lowercase
}
return new_str.toUpperCase(); // Otherwise, return string in uppercase
}

console.log(change_case("Write")); // Output the result of the function for the input "Write"
console.log(change_case("PHp")); // Output the result of the function for the input "PHp"

99. Sắp xếp lại ký tự để khớp chuỗi khác
Kiểm tra liệu có thể hoán vị ký tự của chuỗi A để trở thành chuỗi B hay không.

Code mẫu:

// Function to check if characters of str1 can be rearranged to form str2
function rearrangement_characters(str1, str2) {
// Splitting the strings into arrays of characters
var first_set = str1.split(''), // Array for characters of str1
second_set = str2.split(''), // Array for characters of str2
result = true; // Variable to store the result of rearrangement check

// Sorting the character arrays in ascending order
first_set.sort();
second_set.sort();

// Loop through the arrays to compare each character position
for (var i = 0; i < Math.max(first_set.length, second_set.length); i++) {
// Check if characters at the same position in both arrays are different
if (first_set[i] !== second_set[i]) {
result = false; // Set result to false if characters differ
}
}

return result; // Return the final result of rearrangement check
}
  
// Testing the function with sample strings
console.log(rearrangement_characters("xyz", "zyx")); // Example usage
console.log(rearrangement_characters("xyz", "zyp")); // Example usage 

100. Hai mảng có phần tử chung
Kiểm tra hai mảng số nguyên đã sắp xếp có ít nhất một phần tử chung.

Code mẫu:

// Function to check if there's a common element in two arrays
function check_common_element(arra1, arra2) {
for (var i = 0; i < arra1.length; i++) {
// Check if the current element from arra1 exists in arra2
if (arra2.indexOf(arra1[i]) != -1) {
return true; // If found, return true
}
}
return false; // If no common element is found, return false
}

// Example usage
console.log(check_common_element([1, 2, 3], [3, 4, 5])); // Should return true as 3 is a common element
console.log(check_common_element([1, 2, 3], [5, 6, 7])); // Should return false as no common elements are found 

101. Chỉ chữ cái Latinh, không có hai hoa/thường liền kề
Xác minh chuỗi chỉ gồm chữ cái Latinh và không có hai chữ hoa hoặc hai chữ thường đứng cạnh nhau.

Code mẫu:

// Function to test a string
function test_string(input_str) {

// Function to check if symbol is lowercase
var is_lower_case = function(symbol) {
if ('a' <= symbol && symbol <= 'z') {
return true;
}
return false;
}

// Function to check if symbol is uppercase
var is_upper_case = function(symbol) {
if ('A' <= symbol && symbol <= 'Z') {
return true;
}
return false;
}

// Check if the first character is lowercase or uppercase
var is_first_char_lower = is_lower_case(input_str[0]),
is_first_char_upper = is_upper_case(input_str[0]);

// If the first character is neither lowercase nor uppercase, return false
if (!(is_first_char_lower || is_first_char_upper)) {
return false;
}
// Iterate through the string
for (var i = 1; i < input_str.length; i++) {
// Check odd positions
if (i % 2) {
// Check if the character's case differs from the first character's case
if (is_lower_case(input_str[i]) === is_first_char_lower ||
is_upper_case(input_str[i]) === is_first_char_upper) {
return false; // Return false if cases are the same
}
} else {
// Check if the character's case matches the first character's case
if (is_lower_case(input_str[i]) !== is_first_char_lower ||
is_upper_case(input_str[i]) !== is_first_char_upper) {
return false; // Return false if cases do not match
}
}
}

return true; // Return true if conditions are met for the entire string
}

console.log(test_string('xYr')); // Example usage
console.log(test_string('XXyx')); // Example usage 

102. Đếm số nghịch thế trong mảng
Đếm số cặp (i, j) sao cho i < j và a[i] > a[j].

Code mẫu:

// Function to count the number of inversions in an array (naive approach)
function number_of_InversionsNaive(arr) {
var ctr = 0; // Counter for inversions

// Loop through the array elements
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
// If an inversion is found, increment the counter
if (arr[i] > arr[j]) 
ctr++;
}
}

return ctr; // Return the count of inversions
}

// Test cases
console.log(number_of_InversionsNaive([0, 3, 2, 5, 9])); // Output: 1
console.log(number_of_InversionsNaive([1, 5, 4, 3])); // Output: 3
console.log(number_of_InversionsNaive([10, 30, 20, -10])); // Output: 4 

103. Lớn nhất sau khi xóa đúng một chữ số
Từ số nguyên dương, xóa đúng một chữ số để nhận số lớn nhất.

Code mẫu:

// Function to delete a digit from a given number and return the maximum resulting number
function digit_delete(num) {
var result = 0, // Variable to store the maximum resulting number
num_digits = []; // Array to store individual digits of the number

// Extract digits of the number and store them in an array
while (num) {
num_digits.push(num % 10);
num = Math.floor(num / 10);
}

// Iterate through each digit and generate numbers after deleting each digit
for (var index_num = 0; index_num < num_digits.length; index_num++) {
var n = 0; // Temporary variable to store the generated number

// Create a new number without the current indexed digit
for (var i = num_digits.length - 1; i >= 0; i--) {
if (i !== index_num) {
n = n * 10 + num_digits[i];
}
}

// Store the maximum number obtained after deleting each digit
result = Math.max(n, result);
}

return result; // Return the maximum resulting number
}

// Test cases
console.log(digit_delete(100)); // Example usage
console.log(digit_delete(10)); // Example usage
console.log(digit_delete(1245)); // Example usage

104. Cặp có hiệu tuyệt đối gần nhất ngưỡng k
Chọn hai phần tử sao cho |a − b| ≤ k và càng gần k càng tốt.

Code mẫu:

// Function to find the maximum absolute difference between elements of an array that is less than or equal to a given number
function different_values(ara, n) {
var max_val = -1; // Initializing the maximum value as -1
for (var i = 0; i < ara.length; i++) { // Looping through the array elements
for (var j = i + 1; j < ara.length; j++) { // Nested loop for comparisons with subsequent elements
var x = Math.abs(ara[i] - ara[j]); // Calculating the absolute difference between elements
if (x <= n) { // Checking if the absolute difference is less than or equal to 'n'
max_val = Math.max(max_val, x); // Updating the maximum value if the condition is met
}
}
}
return max_val; // Returning the maximum value found
}

// Examples of using the function with different arrays and values of 'n'
console.log(different_values([12, 10, 33, 34], 10)); // Example usage
console.log(different_values([12, 10, 33, 34], 24)); // Example usage
console.log(different_values([12, 10, 33, 44], 40)); // Example usage 

105. Đếm số lần thay bằng tổng chữ số đến khi còn 1 chữ số
Lặp thay n bằng tổng chữ số của n cho tới khi còn 1 chữ số; đếm số lần lặp.

Code mẫu:

 // Function to calculate the sum of digits in a number
function digit_to_one(num) {
// Inner function to compute the sum of digits in a number
var digitSum = function(num) {
var digit_sum = 0; // Initialize the variable to store the sum of digits
while (num) { // Loop to extract digits and sum them
digit_sum += num % 10; // Add the last digit to the sum
num = Math.floor(num / 10); // Remove the last digit from the number
}
return digit_sum; // Return the sum of digits
};

var result = 0; // Initialize the counter for the number of steps

while (num >= 10) { // Loop until the number becomes a single digit
result += 1; // Increment the counter for each step
num = digitSum(num); // Get the sum of digits and assign it to the number
}

return result; // Return the count of steps required
}

// Example usage of the function
console.log(digit_to_one(123)); 
console.log(digit_to_one(156)); 

106. Chia liên tiếp cho tới khi kết quả không còn nguyên
Chia số nguyên cho số nguyên khác chừng nào kết quả vẫn là số nguyên; trả về kết quả cuối.

Code mẫu:

// Function to divide a number by a digit
function divide_digit(num, d) {
// Check if divisor is 1, return the number itself
if (d == 1)
return num;
else {
// Loop to divide the number by the divisor until not divisible
while (num % d === 0) {
num /= d; // Divide the number by the divisor
}
return num; // Return the final divided number
}
}

// Example usage of the function with different numbers and divisors
console.log(divide_digit(-12, 2)); // Output: -3
console.log(divide_digit(13, 2)); // Output: 13
console.log(divide_digit(13, 1)); // Output: 13 

107. Đếm cặp có tính chia hết (có thứ tự)
Đếm số cặp có thứ tự (x, y) trong mảng sao cho x chia hết y hoặc y chia hết x.

Code mẫu:

// Function to count the number of pairs in an array where one element is a multiple of another
function arr_pairs(arr) {
var result = 0; // Initialize the count of pairs to zero

for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
// Check if either element is a multiple of the other
if (arr[i] % arr[j] === 0 || arr[j] % arr[i] === 0) {
result++; // Increment the count if a pair is found
}
}
}

return result; // Return the total count of pairs
}

// Example usage of the function
console.log(arr_pairs([1, 2, 3])); // Output: 2 (pairs: [1, 2], [1, 3])
console.log(arr_pairs([2, 4, 6])); // Output: 3 (pairs: [2, 4], [2, 6], [4, 6])
console.log(arr_pairs([2, 4, 16])); // Output: 6 (pairs: [2, 4], [2, 16], [4, 16], [4, 16], [4, 16], [4, 16]) 

108. Tích vô hướng hai vector 3D
Tính dot product của hai vector 3 chiều cho trước.

Code mẫu:

// Function to calculate the dot product of two vectors in 3D space
function dot_product(vector1, vector2) {
var result = 0; // Initialize the variable to store the dot product result

// Loop through each component of the vectors and calculate the dot product
for (var i = 0; i < 3; i++) {
result += vector1[i] * vector2[i]; // Sum the products of corresponding components
}

return result; // Return the calculated dot product
}

// Examples of calculating dot products of given vectors
console.log(dot_product([1, 2, 3], [1, 2, 3])); // Output: 14 (1*1 + 2*2 + 3*3 = 14)
console.log(dot_product([2, 4, 6], [2, 4, 6])); // Output: 56 (2*2 + 4*4 + 6*6 = 56)
console.log(dot_product([1, 1, 1], [0, 1, -1])); // Output: 0 (1*0 + 1*1 + 1*(-1) = 0) 

109. Liệt kê số nguyên tố từ 1 đến n
Tạo mảng chứa tất cả số nguyên tố trong [1..n].

Code mẫu:

// Function to sort prime numbers up to 'num'
function sort_prime(num) {
var prime_num1 = [], // Array to store prime numbers
prime_num2 = []; // Array to track prime status (true/false)

// Initialize prime_num2 array to true for all indices from 0 to num
for (var i = 0; i <= num; i++) {
prime_num2.push(true);
}

// Loop to find prime numbers using the Sieve of Eratosthenes algorithm
for (var i = 2; i <= num; i++) {
if (prime_num2[i]) {
prime_num1.push(i); // Push the current number to prime_num1 if it's a prime

// Mark multiples of the current number as non-prime in prime_num2
for (var j = 1; i * j <= num; j++) {
prime_num2[i * j] = false;
}
}
}

return prime_num1; // Return the array containing sorted prime numbers
}

// Example usage of the sort_prime function with different values
console.log(sort_prime(5)); // Output: [2, 3, 5]
console.log(sort_prime(11)); // Output: [2, 3, 5, 7, 11]
console.log(sort_prime(19)); // Output: [2, 3, 5, 7, 11, 13, 17, 19]

110. Đếm số chẵn trước khi gặp giá trị X lần đầu
Đếm bao nhiêu số chẵn xuất hiện trước lần đầu tiên thấy X trong mảng.

Code mẫu:

// Function to count even numbers before the given number in the array
function find_numbers(arr_num, num) {
var result = 0; // Counter variable to store the count of even numbers
for (var i = 0; i < arr_num.length; i++) {
if (arr_num[i] % 2 === 0 && arr_num[i] !== num) { // Check if number is even and not equal to 'num'
result++; // Increment the counter for each even number
}
if (arr_num[i] === num) { // Check if the current number matches 'num'
return result; // Return the count of even numbers encountered so far
}
}
return -1; // Return -1 if 'num' is not found in the array
}

// Example usage of the function
console.log(find_numbers([1, 2, 3, 4, 5, 6, 7, 8], 5)); 
console.log(find_numbers([1, 3, 5, 6, 7, 8], 6)); 

111. Tìm số khác biệt trong ba số (hai số trùng nhau)
Trong ba số có hai số bằng nhau, hãy trả về số còn lại.

Code mẫu:

// Function to find the third number that is different from the other two given numbers
function find_third_number(x, y, z) {
// Check if all three numbers are unequal
if ((x !== y) && (x !== z) && (y !== z)) {
return "Three numbers are unequal."; // Return a message if all three numbers are unequal
} 

// Check if the first number is equal to the second number
if (x === y) {
return z; // Return the third number if the first and second numbers are equal
}

// Check if the first number is equal to the third number
if (x === z) {
return y; // Return the second number if the first and third numbers are equal
}

return x; // Return the first number (default case when second and third numbers are equal)
}

// Example usage of the function
console.log(find_third_number(1, 2, 2)); // Output: 1 (the third number different from the other two: 1)
console.log(find_third_number(1, 1, 2)); // Output: 2 (the third number different from the other two: 2)
console.log(find_third_number(1, 2, 3)); // Output: "Three numbers are unequal." (all three numbers are different) 

112. Số lượng số 0 tận cùng của n!
Tính số chữ số 0 ở cuối khi viết giai thừa n theo hệ thập phân.

Code mẫu:

// Function to count trailing zeros in the factorial of a number
function trailing_zeros_factorial(n) {
var result = 0; // Initialize the count of trailing zeros to zero
for (var i = 5; i <= n; i += 5) { // Loop to calculate the factorial
var num = i; // Store the current number
while (num % 5 === 0) { // Check if the number is divisible by 5
num /= 5; // Divide the number by 5
result++; // Increment the count of trailing zeros
}
}
return result; // Return the total count of trailing zeros in the factorial of n
}

// Examples of using the function with different values
console.log(trailing_zeros_factorial(8)); // Output: 1 (factorial of 8 has one trailing zero)
console.log(trailing_zeros_factorial(9)); // Output: 1 (factorial of 9 has one trailing zero)
console.log(trailing_zeros_factorial(10)); // Output: 2 (factorial of 10 has two trailing zeros)

113. Tính n + n/2 + n/4 + … (chia lấy nguyên)
Cộng chuỗi n + ⌊n/2⌋ + ⌊n/4⌋ + … cho tới 0.

Code mẫu:

// Function to calculate the sum of integers from 1 to num using bitwise operation
function int_sum(num) {
var s_sum = 0; // Initialize the sum variable
while (num > 0) { // Loop until num is greater than 0
s_sum += num; // Add num to the sum
num = Math.floor(num / 2); // Divide num by 2 using floor division
}
return s_sum; // Return the sum of integers from 1 to num
}

// Examples to calculate the sum of integers from 1 to the given number
console.log(int_sum(8)); 
console.log(int_sum(9)); 
console.log(int_sum(26)); 

114. Chuỗi có phải câu đúng?
Kiểm tra chuỗi bắt đầu bằng chữ in hoa và kết thúc bằng dấu chấm.

Code mẫu:

// Check if the input string is a correct sentence based on certain conditions
function is_correct_Sentence(input_str) {
var first_char = input_str[0]; // Get the first character of the string
var last_char = input_str[input_str.length - 1]; // Get the last character of the string
return /[A-Z]/.test(first_char) && last_char == "."; // Check if the first character is an uppercase letter and the last character is a period.
}

// Examples of checking correct sentences using the function
console.log(is_correct_Sentence("This tool will help you write better English and efficiently corrects texts.")); // Output: true (It's a correct sentence)
console.log(is_correct_Sentence("This tool will help you write better English and efficiently corrects texts")); // Output: false (Missing period at the end)
console.log(is_correct_Sentence("this tool will help you write better English and efficiently corrects texts.")); // Output: false (First letter should be capitalized)

115. Ma trận đường chéo
Kiểm tra ma trận vuông: mọi phần tử ngoài đường chéo chính đều bằng 0.

Code mẫu:

// Function to check if a matrix is a diagonal matrix
const is_diagonal_matrix = (user_matrix) => {
// Loop through each row of the matrix
for (let i = 0; i < user_matrix.length; i++) {
// Loop through each element in the row
for (let j = 0; j < user_matrix.length; j++) {
// Check if the element is non-zero when it's not on the diagonal (i !== j)
if (i !== j && user_matrix[i][j] !== 0) 
return false; // Return false if non-zero value is found off the diagonal
}
}
return true; // Return true if all non-diagonal elements are zero
}

// Testing the function with sample matrix inputs
console.log(is_diagonal_matrix([[1, 0, 0], [0, 2, 0], [0, 0, 3]])); // Output: true (Diagonal matrix)
console.log(is_diagonal_matrix([[1, 0, 0], [0, 2, 3], [0, 0, 3]])); // Output: false (Non-diagonal elements present) 

116. Thay ‘#’ để số chia hết cho 3
Với chuỗi gồm chữ số và một ‘#’, tìm mọi thay thế ‘#’ bằng chữ số để số kết quả chia hết cho 3.

Code mẫu:

// Function to generate strings by replacing '#' in the input with digits making the resulting number divisible by 3
function is_divisible_by3(mask_str) {
var digitSum = 0, // Variable to hold the sum of digits in the mask string
left = '0'.charCodeAt(), // ASCII code of '0'
right = '9'.charCodeAt(), // ASCII code of '9'
result = [], // Array to store the resulting strings
mask_data = mask_str.split(''), // Split the input mask string into an array
hash_pos = -1; // Position of the '#' character

// Loop through the characters in the mask string array
for (var i = 0; i < mask_data.length; i++) {
if (left <= mask_data[i].charCodeAt() && mask_data[i].charCodeAt() <= right) {
digitSum += mask_data[i].charCodeAt() - left; // Calculate digit sum if character is a digit
} else {
hash_pos = i; // Store the position of '#' character
}
}

// Loop through numbers 0 to 9 to replace '#' with digits making the number divisible by 3
for (var i = 0; i < 10; i++) {
if ((digitSum + i) % 3 === 0) { // Check if the sum of digits with the new digit is divisible by 3
mask_data[hash_pos] = String.fromCharCode(left + i); // Replace '#' with the new digit
result.push(mask_data.join('')); // Push the modified mask string to the result array
}
}

return result; // Return the array containing strings with the '#' replaced by digits
}

// Testing the function with sample inputs
console.log(is_divisible_by3("2#0")); // Output: [ '210', '240', '270' ]
console.log(is_divisible_by3("4#2")); // Output: [ '402', '432', '462', '492' ] 

117. Ma trận đơn vị
Kiểm tra ma trận có 1 trên đường chéo chính và 0 ở vị trí khác hay không.

Code mẫu:

// Function to check if the given matrix is an identity matrix
function is_identity_Matrix(matrix_data) {
// Checks whether given matrix is a square matrix or not
for (var i = 0; i < matrix_data.length; i++) {
rows = matrix_data.length;
cols = matrix_data[i].length;
if (rows != cols) {
console.log("Matrix should be a square matrix");
return false;
}
}
// Loop to verify if the matrix is an identity matrix
for (var i = 0; i < matrix_data.length; i++) {
for (var j = 0; j < matrix_data.length; j++) {
if (matrix_data[i][j] !== 1 && i === j || matrix_data[i][j] && i !== j) {
return false;
}
}
}
return true; // Returns true if the matrix is an identity matrix
}

// Testing the function with sample inputs
console.log(is_identity_Matrix([[1, 0, 0, 2], [0, 1, 0], [0, 0, 1]])); // Output: false (not a square matrix)
console.log(is_identity_Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])); // Output: true (identity matrix)
console.log(is_identity_Matrix([[1, 0, 1], [0, 1, 0], [0, 0, 1]])); // Output: false (not an identity matrix) 

118. Số nằm trong một khoảng cho trước
Kiểm tra số x có thuộc [l, r] hay không.

Code mẫu:

// Function to check if 'y' lies within the range of 'x' and 'z'
function is_inrange(x, y, z) 
{
return y >= x && y <= z; // Returns true if 'y' is between 'x' and 'z' (inclusive)
}

console.log(is_inrange(1,2,3)); // Output: true (2 is in the range between 1 and 3)
console.log(is_inrange(1,2,-3)); // Output: false (2 is not in the range between 1 and -3)
console.log(is_inrange(1.1,1.2,1.3)); // Output: true (1.2 is in the range between 1.1 and 1.3) 

119. Các chữ số tăng dần
Kiểm tra các chữ số của số nguyên có tăng (không giảm) theo thứ tự trái→phải hay không.

Code mẫu:

// Function to check if the digits of a number form an increasing sequence
function is_increasing_digits_Sequence(num) {
var arr_num = ('' + num).split(''); // Convert the number to a string and split it into an array of digits

// Loop through the array of digits
for (var i = 0; i < arr_num.length - 1; i++) {
// Check if the current digit is greater than or equal to the next digit
if (parseInt(arr_num[i]) >= parseInt(arr_num[i + 1])) {
return false; // If the sequence is not increasing, return false
}
}
return true; // If the sequence is increasing, return true
}

// Test cases
console.log(is_increasing_digits_Sequence(123)); // Output: true (Each digit forms an increasing sequence)
console.log(is_increasing_digits_Sequence(1223)); // Output: false (Digits are not in strictly increasing order)
console.log(is_increasing_digits_Sequence(45677)); // Output: false (Digits are not in strictly increasing order)

120. Điểm nằm trong đường tròn
Cho tâm (x, y), bán kính r, kiểm tra điểm (a, b) có nằm trong hình tròn.

Code mẫu:

// Function to check if a point (a, b) is inside a circle with center (x, y) and radius r
function check_a_point(a, b, x, y, r) {
// Calculate the squared distance between the center of the circle (x, y) and the point (a, b)
var dist_points = (a - x) * (a - x) + (b - y) * (b - y); 

// Square the radius for comparison
r *= r; 

// Check if the squared distance between points is less than the squared radius
if (dist_points < r) {
return true; // Point is inside the circle
}
return false; // Point is outside the circle or on the circle
}

// Test cases
console.log(check_a_point(0, 0, 2, 4, 6)); // Output: true (Point (0,0) is inside the circle with center (2,4) and radius 6)
console.log(check_a_point(0, 0, 6, 8, 6)); // Output: false (Point (0,0) is outside the circle with center (6,8) and radius 6) 

121. Ma trận tam giác dưới
Kiểm tra ma trận vuông: mọi phần tử phía trên đường chéo chính bằng 0.

Code mẫu:

// Function to check if a matrix is a lower triangular matrix
function lower_triangular_matrix(user_matrix) {
for (var i = 0; i < user_matrix.length; i++) {
for (var j = 0; j < user_matrix[0].length; j++) {
// If element is above the main diagonal and not equal to zero, return false
if (j > i && user_matrix[i][j] !== 0) {
return false;
} 
}
}
return true; // Matrix is lower triangular
}

// Test cases
console.log(lower_triangular_matrix([[1, 0, 0],[2, 0, 0], [0, 3, 3]])); // Output: true (Lower triangular matrix)
console.log(lower_triangular_matrix([[1, 0, 1],[2, 0, 0], [0, 3, 3]])); // Output: false (Not a lower triangular matrix)

122. Mảng tăng/giảm nghiêm ngặt
Xác định mảng có tăng strict hoặc giảm strict từ đầu tới cuối.

Code mẫu:

// Function to check if a sequence of numbers is monotonous
function is_monotonous(num) {
// If the sequence has only one element, it's considered monotonous
if (num.length === 1) {
return true;
}

// Calculate the direction of the sequence
var num_direction = num[1] - num[0];

// Check for non-monotonic behavior
for (var i = 0; i < num.length - 1; i++) {
// If the product of direction and the difference between elements is not positive, it's non-monotonic
if (num_direction * (num[i + 1] - num[i]) <= 0) {
return false;
}
}
// If the loop completes, the sequence is monotonic
return true;
}

// Test cases
console.log(is_monotonous([1, 2, 3])); // Output: true (Monotonously increasing)
console.log(is_monotonous([1, 2, 2])); // Output: false (Not strictly increasing)
console.log(is_monotonous([-3, -2, -1])); // Output: true (Monotonously increasing) 

123. Hoán vị các số từ 1 đến n
Kiểm tra mảng có phải hoán vị của 1..n (không trùng, đủ phần tử) hay không.

Code mẫu:

// Function to check if input array is a permutation of [1, 2, 3, ..., n]
function is_permutation(input_arr, n) {
// Loop through each element from 1 to n
for (var i = 0; i < n; i++) {
// Check if the current element is not found in the input array
if (input_arr.indexOf(i + 1) < 0) {
return false; // If not found, it's not a permutation
}
}
return true; // If all elements are found, it's a permutation
}

// Test cases
console.log(is_permutation([1, 2, 3, 4, 5], 5)); // Output: true (permutation of [1, 2, 3, 4, 5])
console.log(is_permutation([1, 2, 3, 5], 5)); // Output: false (not a permutation of [1, 2, 3, 4, 5]) 

124. Toán tử NOR hai giá trị boolean
Tính p NOR q (đúng khi và chỉ khi cả p và q đều sai).

Code mẫu:

// Function to perform logical NOR operation
function test_logical_Nor(a, b) {
return (!a && !b); // Returns true only if both a and b are false
}

// Testing logical NOR operation with different input values
console.log(test_logical_Nor(true, false)); // Output: false (logical NOR of true and false is false)
console.log(test_logical_Nor(false, false)); // Output: true (logical NOR of false and false is true)
console.log(test_logical_Nor(true, true)); // Output: false (logical NOR of true and true is false) 

125. Chuỗi dài nhất trong mảng chuỗi
Tìm phần tử có độ dài lớn nhất trong mảng string.

Code mẫu:

// Function to find the longest string in an array
function longest_str_in_array(arra) {
var max_str = arra[0].length; // Initialize max_str with the length of the first string
var ans = arra[0]; // Initialize ans with the first string

// Loop through the array starting from the second element
for (var i = 1; i < arra.length; i++) {
var maxi = arra[i].length; // Get the length of the current string

// Compare the length of the current string with max_str
if (maxi > max_str) {
ans = arra[i]; // If current string is longer, update ans
max_str = maxi; // Update max_str with the new maximum length
}
}

return ans; // Return the longest string found
}

// Testing the function with different arrays
console.log(longest_str_in_array(["ab", "a", "abcd"])); // Output: "abcd" (Longest string in the array)
console.log(longest_str_in_array(["ab", "ab", "ab"])); // Output: "ab" (All strings are of equal length) 

126. Số chẵn lớn nhất trong mảng
Trả về số chẵn lớn nhất từ mảng số nguyên.

Code mẫu:

// Function to find the maximum even number in an array
function max_even(arra) {
// Sort the array in descending order
arra.sort((x, y) => y - x);

// Loop through the array
for (var i = 0; i < arra.length; i++) {
// Check if the current number is even
if (arra[i] % 2 == 0)
return arra[i]; // If even, return the number
}
}

// Testing the function with different arrays
console.log(max_even([20, 40, 200])); // Output: 200 (The maximum even number in the array)
console.log(max_even([20, 40, 200, 301])); // Output: 200 (The maximum even number in the array) 

127. Đảo thứ tự bit của số nguyên
Đảo ngược thứ tự bit (theo độ dài cố định) của một số nguyên.

Code mẫu:

// Function to mirror bits of a given number
function mirror_bits(n) {
// Convert number to binary and split into array of bits
let t = n.toString(2).split(""); 

// Get the length of the binary string
let str_len = t.length;

// Add leading zeroes to make the length of the binary string 8
for (let i = 0; i < 8 - str_len; i++) {
t.unshift("0");
}

// Reverse the bits and convert the binary string back to a number
return parseInt(t.reverse().join(""), 2);
}

// Test cases with comments showing the step-by-step process
// 14 -> 00001110 -> 01110000 -> 112
console.log(mirror_bits(14));
// 56 -> 00111000 -> 00011100 -> 28
console.log(mirror_bits(56));
// 234 -> 11101010 -> 01010111 -> 87
console.log(mirror_bits(234));

128. Số “tròn” nhỏ nhất ≥ giá trị cho trước
Tìm số kết thúc bằng một/multiple số 0 nhỏ nhất nhưng không nhỏ hơn giá trị cho trước.

Code mẫu:

// Function to find the nearest round number
function nearest_round_number(num) {
// Loop until the number is divisible by 10
while (num % 10) {
// Increment the number by 1 until it is divisible by 10
num++;
}
// Return the nearest round number
return num;
}

// Test cases
console.log(nearest_round_number(56)); // Output: 60
console.log(nearest_round_number(592)); // Output: 600

129. Nguyên tố nhỏ nhất > x
Tìm số nguyên tố nhỏ nhất lớn hơn một số x.

Code mẫu:

// Function to find the next prime number after a given number
function next_Prime_num(num) {
// Start checking from the next number after 'num'
for (var i = num + 1;; i++) {
var isPrime = true;
// Check divisibility from 2 up to the square root of the number
for (var d = 2; d * d <= i; d++) {
// If 'i' is divisible by 'd', it's not a prime number
if (i % d === 0) {
isPrime = false;
break;
}
}
// If 'isPrime' is still true, return 'i' (it's a prime number)
if (isPrime) {
return i;
}
}
}

// Test cases
console.log(next_Prime_num(3)); // Output: 5
console.log(next_Prime_num(17)); // Output: 19 

130. Đếm chữ số chẵn trong số
Đếm bao nhiêu chữ số chẵn trong biểu diễn thập phân của số nguyên.

Code mẫu:

// Function to count the number of even digits in a given number
function even_digits(num) {
var ctr = 0;
// Loop until 'num' becomes 0
while (num) {
// Increment 'ctr' if the last digit of 'num' is even
ctr += num % 2 === 0;
// Remove the last digit by integer division
num = Math.floor(num / 10);
}
return ctr; // Return the count of even digits
}

// Test cases
console.log(even_digits(123)); // Output: 1
console.log(even_digits(1020)); // Output: 3
console.log(even_digits(102)); // Output: 2 

131. Mảng tổng tiền tố (prefix sum)
Tạo mảng y sao cho y[i] = x[0] + … + x[i].

Code mẫu:

// Function to compute prefix sums of an array
function prefix_sums(arr) {
var new_arr = []; // Initialize an empty array to store prefix sums 

// Loop through the input array
for (var i = 0; i < arr.length; i++) {
new_arr[i] = 0; // Initialize each element in the new array to 0 

// Compute the prefix sum up to index 'i' in the input array
for (var j = 0; j < i + 1; j++) {
new_arr[i] += arr[j]; // Sum the elements from index 0 to 'i'
}
} 

return new_arr; // Return the array containing prefix sums
}

// Test cases
console.log(prefix_sums([1, 2, 3, 4, 5])); // Output: [1, 3, 6, 10, 15]

console.log(prefix_sums([1, 2, -3, 4, 5])); // Output: [1, 3, 0, 4, 9]

132. Các ước nguyên tố phân biệt
Liệt kê các thừa số nguyên tố khác nhau của một số nguyên.

Code mẫu:

// Function to find prime factors of a number
function prime_factors(num) {
// Function to check if a number is prime
function is_prime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false; // If the number is divisible by any number other than 1 and itself, it's not a prime
}
return true; // Return true if the number is prime
}

const result = []; // Initialize an empty array to store prime factors 

// Loop through numbers from 2 to 'num'
for (let i = 2; i <= num; i++) {
// While 'i' is a prime factor and divides 'num' evenly
while (is_prime(i) && num % i === 0) {
if (!result.includes(i)) result.push(i); // Add 'i' to the result array if it's not already present
num /= i; // Divide 'num' by 'i'
}
} 

return result; // Return the array containing prime factors
}

// Test cases
console.log(prime_factors(100)); // Output: [2, 5]
console.log(prime_factors(101)); // Output: [101]
console.log(prime_factors(103)); // Output: [103]
console.log(prime_factors(104)); // Output: [2, 13]
console.log(prime_factors(105)); // Output: [3, 5, 7] 

133. Phân số đúng hay không đúng
Cho phân số dương a/b, kiểm tra a < b (đúng) hay a ≥ b (không đúng).

Code mẫu:

// Function to determine if the fraction is proper or improper
function proper_improper_test(num) {
// Check if the absolute value of the division is less than 1
return Math.abs(num[0] / num[1]) < 1
? "Proper fraction." // Return 'Proper fraction.' if the condition is true
: "Improper fraction."; // Otherwise, return 'Improper fraction.'
}

// Test cases
console.log(proper_improper_test([12, 300])); // Output: Proper fraction.
console.log(proper_improper_test([2, 4])); // Output: Proper fraction.
console.log(proper_improper_test([103, 3])); // Output: Improper fraction.
console.log(proper_improper_test([104, 2])); // Output: Improper fraction.
console.log(proper_improper_test([5, 40])); // Output: Proper fraction.

134. Ánh xạ chữ thường đảo bảng chữ cái
Biến a→z, b→y, …, m↔n, …, z→a cho toàn bộ chữ thường trong chuỗi.

Code mẫu:

// Function to change characters in a string based on specified logic
function change_char(str1) {
var result = []; // Initialize an empty array to store the resulting characters
for (var i = 0; i < str1.length; i++) {
var char_order = str1.charCodeAt(i) - 'a'.charCodeAt(0); // Get the character code and calculate its order relative to 'a'
var change_char = 25 - char_order + 'a'.charCodeAt(0); // Calculate the new character based on the order difference
result.push(String.fromCharCode(change_char)); // Convert the character code back to character and add it to the result array
}
return result.join(""); // Join the characters in the result array into a string and return
}

// Test cases
console.log(change_char("abcxyz")); // Output: "zyxcba"
console.log(change_char("python")); // Output: "kbgslm" 

135. Xóa ký tự lặp lại
Loại bỏ các ký tự xuất hiện nhiều lần, chỉ giữ mỗi ký tự một lần.

Code mẫu:

/**
* Function to remove duplicate characters from a string
* @param {string} str - The input string
* @returns {string} - The string without duplicate characters
*/
function remove_duplicate_chars(str) {
// Split the string into an array of characters
var arr_char = str.split("");
var result_arr = [];

// Loop through each character of the array
for (var i = 0; i < arr_char.length; i++) {
// Check if the first and last occurrence of a character in the string are the same
if (str.indexOf(arr_char[i]) === str.lastIndexOf(arr_char[i]))
result_arr.push(arr_char[i]);
}

// Join the array of unique characters and return as a string
return result_arr.join("");
}

console.log(remove_duplicate_chars("abcdabc"));
console.log(remove_duplicate_chars("python"));
console.log(remove_duplicate_chars("abcabc"));
console.log(remove_duplicate_chars("1365451"));

136. Thay chữ số đầu tiên bằng ‘$’
Trong chuỗi có ít nhất một chữ số, thay chữ số đầu tiên gặp được bằng ký tự ‘$’.

Code mẫu:

/**
* Function to replace the first digit in a string with '$'
* @param {string} input_str - The input string
* @returns {string} - The modified string with the first digit replaced by '$'
*/
function replace_first_digit(input_str) {
// Using regular expression to replace the first occurrence of a digit with '$'
return input_str.replace(/[0-9]/, '$');
}

console.log(replace_first_digit("abc1dabc")); // Output: "abc$dabc"
console.log(replace_first_digit("p3ython")); // Output: "p$ython"
console.log(replace_first_digit("ab1cabc")); // Output: "ab$cabc" 

137. Trả về số nếu >15, ngược lại trả 15
Nếu n > 15 trả về n, không thì trả 15.

Code mẫu:

/**
* Function to increment 'num' until it reaches or exceeds 15
* @param {number} num - The input number
* @returns {number} - The updated number (num >= 15)
*/
function test_fifteen(num) {
while (num < 15) { // Loop continues until 'num' reaches or exceeds 15
num++; // Increment 'num' by 1
}
return num; // Return the updated 'num'
}

console.log(test_fifteen("123")); // Output: 123 (input not converted to a number)
console.log(test_fifteen("10")); // Output: 15 (input incremented until 15)
console.log(test_fifteen("5")); // Output: 15 (input incremented until 15)

138. Đảo bit của số 16-bit không dấu
Đảo ngược thứ tự 16 bit của một giá trị không dấu.

Code mẫu:

/**
* Function to reverse the binary representation of a 16-bit number
* @param {number} num - The input number
* @returns {number} - The reversed binary number
*/ 
function sixteen_bits_reverse(num) {
var result = 0; // Initialize result to store the reversed number
for (var i = 0; i < 16; i++) {
result = result * 2 + (num % 2); // Reversing the bits by shifting result left and adding the last bit of 'num'
num = Math.floor(num / 2); // Right-shifting 'num' to access the next bit
}
return result; // Return the reversed 16-bit number
}

console.log(sixteen_bits_reverse(12345)); 
console.log(sixteen_bits_reverse(10)); 
console.log(sixteen_bits_reverse(5)); 

139. Vị trí số “tròn” ngoài cùng bên phải
Tìm chỉ số của phần tử cuối cùng kết thúc bằng 0; nếu không có, trả 0.

Code mẫu:

/**
* Function to find the index of the rightmost round number (divisible by 10) in the array
* @param {number[]} input_arr - The input array of numbers
* @returns {number} - The index of the rightmost round number (if found)
*/
function find_rightmost_round_number(input_arr) {
var result = 0; // Variable to store the index of the rightmost round number (default: 0)
for (var i = 0; i < input_arr.length; i++) {
if (input_arr[i] % 10 === 0) { // Checking if the number is divisible by 10
result = i; // Updating 'result' with the current index if the number is divisible by 10
}
}
return result; // Returning the index of the rightmost round number
}

console.log(find_rightmost_round_number([1, 22, 30, 54, 56])); 
console.log(find_rightmost_round_number([1, 22, 32, 54, 56])); 
console.log(find_rightmost_round_number([1, 22, 32, 54, 50])); 

140. Tất cả chữ số có giống nhau?
Kiểm tra mọi chữ số của số cho trước có cùng một giá trị.

Code mẫu:

/**
* Function to test if all digits in the number are the same
* @param {number} num - The input number
* @returns {boolean} - Returns true if all digits are the same, false otherwise
*/
function test_same_digit(num) {
var first = num % 10; // Extracting the last digit as a reference
while (num) {
if (num % 10 !== first) return false; // Checking if the current digit is different from the reference
num = Math.floor(num / 10); // Removing the last digit by integer division
}
return true; // Returning true if all digits are the same
}

console.log(test_same_digit(1234)); // Output: false
console.log(test_same_digit(1111)); // Output: true
console.log(test_same_digit(22222222)); // Output: true 

141. Số phần tử chung của hai mảng
Đếm bao nhiêu phần tử xuất hiện trong cả hai mảng.

Code mẫu:

/**
* Function to count the number of same elements in both arrays
* @param {Array} arra1 - The first input array
* @param {Array} arra2 - The second input array
* @returns {number} - Returns the count of same elements between the arrays
*/
function test_same_elements_both_arrays(arra1, arra2) {
var result = 0; // Counter to store the count of same elements

// Loop through the first array
for (var i = 0; i < arra1.length; i++) {
// Loop through the second array
for (var j = 0; j < arra2.length; j++) {
if (arra1[i] === arra2[j]) {
result++; // Increment the counter if the elements match
}
}
}
return result; // Return the count of same elements
}

console.log(test_same_elements_both_arrays([1, 2, 3, 4], [1, 2, 3, 4])); // Output: 4
console.log(test_same_elements_both_arrays([1, 2, 3, 4], [1, 2, 3, 5])); // Output: 3
console.log(test_same_elements_both_arrays([1, 2, 3, 4], [11, 22, 33, 44])); // Output: 0 

142. Rút gọn đường dẫn tuyệt đối kiểu Unix
Chuẩn hóa đường dẫn (xử lý ./..///) thành dạng tối giản.

Code mẫu:

/**
* Function to simplify a given path
* @param {string} main_path - The main path to simplify
* @returns {string} - Returns the simplified path
*/
function simplify_path(main_path) {
// Splitting the path into parts
var parts = main_path.split('/'),
new_path = [], // Array to store the simplified path
length = 0; // Variable to keep track of the length of the new path

// Loop through each part of the path
for (var i = 0; i < parts.length; i++) {
var part = parts[i];

// Conditions to handle special cases ('.', '..', '')
if (part === '.' || part === '' || part === '..') {
if (part === '..' && length > 0) {
length--; // Move back one directory level
}
continue; // Skip to the next part
}

new_path[length++] = part; // Store the valid part in the new path array
}

// If the new path is empty, return the root path '/'
if (length === 0) {
return '/';
}

// Reconstructing the simplified path
var result = '';
for (var i = 0; i < length; i++) {
result += '/' + new_path[i]; // Append parts of the new path separated by '/'
}

return result; // Return the simplified path
}

console.log(simplify_path("/home/var/./www/../html//sql/")); // Output: '/home/var/html/sql' 

143. Sắp xếp chuỗi theo độ dài tăng dần
Sắp xếp mảng chuỗi theo độ dài; giữ nguyên thứ tự tương đối khi độ dài bằng nhau.

Code mẫu:

/**
* Function to sort an array of strings based on string length
* @param {array} arra - The array of strings to be sorted
* @returns {array} - The sorted array of strings
*/
function sort_by_string_length(arra) {
// Loop through each element in the array
for (var i = 0; i < arra.length; i++) {
// Compare the current element with the subsequent elements
for (var j = i + 1; j < arra.length; j++) {
// If the length of the current element is greater than the subsequent element
if (arra[i].length > arra[j].length) {
var m = arra[i]; // Store the current element in a temporary variable
arra[i] = arra[j]; // Swap the current element with the subsequent element
arra[j] = m; // Place the temporary variable (previous value of current element) in the subsequent element
}
}
}
return arra; // Return the sorted array
}

var arra = ["xyz", "acd", "aa", "bb", "zzz", "", "a", "b"]; // Input array
console.log("Original array: " + arra + "\n"); // Display original array
console.log(sort_by_string_length(["xyz", "acd", "aa", "bb", "zzz", "", "a", "b"])); // Sort and display the array 

144. Phân tách URL thành các phần
Tách URL thành protocol, host, domain, path…; đưa các phần vào mảng.

Code mẫu:

/**
* Function to break down a URL address into protocol, domain, and optional path
* @param {string} url_add - The URL address to be broken down
* @returns {array} - An array containing protocol, domain, and optional path (if available)
*/
function break_address(url_add) {
// Splitting the URL to separate protocol and the rest of the address
var data = url_add.split("://");
var protocol = data[0]; 

// Splitting the rest of the address to extract domain and possible path
data = data[1].split(".com");
var domain = data[0]; 

// Splitting the address after .com to extract the path if available
data = data[1].split("/");

// Checking if a path exists and returning the relevant parts
if (data[1]) {
return [protocol, domain, data[1]];
}

// Returning protocol and domain if path doesn't exist
return [protocol, domain];
}

// Sample URL address
var url_add = "https://www.w3resource.com/javascript-exercises/";

// Display original address
console.log("Original address: " + url_add);

// Display the broken down parts of the address
console.log(break_address(url_add)); 

145. Tìm n lớn nhất sao cho 1+2+…+n ≤ X
Xác định n tối đa thỏa tổng dãy tự nhiên không vượt quá X.

Code mẫu:

/**
* Function to find the sum of natural numbers up to a given value
* @param {number} val - The value up to which the sum of natural numbers needs to be calculated
* @returns {number} - The number of terms in the sum sequence
*/
function sumn(val) {
var sn = 0; // Initialize the sum of natural numbers
var i = 0; // Initialize the index to 0 
// Loop to calculate the sum of natural numbers up to a certain limit
while (sn <= val) {
sn += i++; // Incrementally add the value of 'i' to the sum and increment 'i'
} 

return i - 2; // Return the number of terms in the sum sequence (subtracting 2 to account for the extra iteration)
}

// Display the number of terms for different values
console.log(sumn(11)); // Output: 4
console.log(sumn(15)); // Output: 5 

146. Tổng lập phương từ 1 đến n
Tính 1³ + 2³ + … + n³.

Code mẫu:

/**
* Function to calculate the sum of cubes up to a given number 'n'
* @param {number} n - The number up to which the sum of cubes needs to be calculated
* @returns {number} - The sum of cubes up to the given number
*/
function sum_Of_Cubes(n) {
var sumn = 0; // Variable to hold the sum of cubes

// Loop to calculate the sum of cubes up to the number 'n'
for (var i = 1; i <= n; i++) {
sumn += Math.pow(i, 3); // Add the cube of 'i' to the sum
}
return sumn; // Return the total sum of cubes
}

// Display the sum of cubes for different values of 'n'
console.log(sum_Of_Cubes(3)); // Output: 36
console.log(sum_Of_Cubes(4)); // Output: 100 

147. Tổng các chữ số xuất hiện trong chuỗi
Cộng tất cả ký tự số (0–9) xuất hiện trong chuỗi.

Code mẫu:

/**
* Function to calculate the sum of digits from a string
* @param {string} dstr - The string containing alphanumeric characters
* @returns {number} - The sum of digits found in the string
*/
function sum_digits_from_string(dstr) {
var dsum = 0; // Variable to hold the sum of digits

for (var i = 0; i < dstr.length; i++) {
// Check if the character is a digit, then convert and add it to 'dsum'
if (/[0-9]/.test(dstr[i])) dsum += parseInt(dstr[i]);
}
return dsum; // Return the sum of digits from the string
}

// Display the sum of digits for different strings
console.log(sum_digits_from_string("abcd12efg9")); // Output: 12
console.log(sum_digits_from_string("w3resource")); // Output: 3 

148. Hoán đổi hai nửa mảng chẵn phần tử
Với mảng có độ dài chẵn, đổi chỗ nửa đầu và nửa sau.

Code mẫu:

/**
* Function to swap the halves of an array
* @param {Array} iarra - The input array
* @returns {(boolean|Array)} - Swapped array if even length, otherwise false
*/
function halv_array_swap(iarra) {
// Check if the array length is even
if ((iarra.length % 2) !== 0) {
return false; // Return false if the array length is odd
}

// Swap the halves of the array
for (var i = 0; i < iarra.length / 2; i++) {
var tmp = iarra[i]; // Temporary variable to store the current element
iarra[i] = iarra[i + iarra.length / 2]; // Swap the first half with the second half
iarra[i + iarra.length / 2] = tmp; // Swap the second half with the first half
}
return iarra; // Return the swapped array
}

// Test cases
console.log(halv_array_swap([1, 2, 3, 4, 5, 6])); // Output: [4, 5, 6, 1, 2, 3]
console.log(halv_array_swap([1, 2, 3, 4, 5, 6, 7])); // Output: false 

149. Đảo kiểu chữ (hoa ↔ thường)
Chuyển toàn bộ chữ cái: hoa thành thường, thường thành hoa.

Code mẫu:

/**
* Function to change the case of characters in a string
* @param {string} txt - The input string
* @returns {string} - The string with changed case characters
*/
function change_case(txt) {
var str1 = "";
// Loop through each character in the input string
for (var i = 0; i < txt.length; i++) {
// Check if the character is uppercase, change to lowercase; otherwise, change to uppercase
if (/[A-Z]/.test(txt[i])) str1 += txt[i].toLowerCase();
else str1 += txt[i].toUpperCase();
}
return str1; // Return the modified string
}

// Test cases
console.log(change_case("w3resource")); // Output: W3RESOURCE
console.log(change_case("Germany")); // Output: gERMANY

150. Hoán đổi từng cặp chữ số liền kề (độ dài chẵn)
Với số có số chữ số chẵn, đổi chỗ từng cặp chữ số cạnh nhau.

Code mẫu:

/**
* Function to swap adjacent digits of a number
* @param {number} n - The input number
* @returns {(number|boolean)} - The number with adjacent digits swapped or `false` if the length is odd
*/
function swap_adjacent_digits(n) {
// Check if the length of the number is odd, return `false` in such cases
if (n.toString().length % 2 != 0) {
return false;
}
var result = 0,
x = 1;
// Loop until the number becomes zero
while (n != 0) {
// Get the last digit (dg1) and the second last digit (dg2)
var dg1 = n % 10,
dg2 = ((n - dg1) / 10) % 10;
// Swap dg1 and dg2, add to the result with appropriate position
result += x * (10 * dg1 + dg2);
// Remove the last two digits from the number
n = Math.floor(n / 100);
// Increment the multiplier x by 100
x *= 100;
}
return result; // Return the number with swapped adjacent digits
}

// Test cases
console.log(swap_adjacent_digits(15)); 
console.log(swap_adjacent_digits(1234)); 
console.log(swap_adjacent_digits(123456)); 
console.log(swap_adjacent_digits(12345)); 

Tạm kết: học tốt đến từ thói quen luyện tập mỗi ngày – và bài tập JavaScript chính là “phòng gym” cho não lập trình. Hãy bắt đầu từ những thử thách nhỏ, kiên trì tăng độ khó và áp dụng vào dự án thật để thấy mình lên level rõ rệt. Nếu bạn muốn được kèm cặp lộ trình, mentor hỗ trợ và thực hành theo dự án, đăng ký chương trình tại CodeGym Đà Nẵng ngay hôm nay để được tư vấn và nhận bộ bài tập + code mẫu đầy đủ!

Đăng ký ngay để được tư vấn miễn phí

4 + 7 =

Tags: bài tập DOM, bài tập hàm JS, bài tập JavaScript, bài tập JavaScript có lời giải, bài tập JS cơ bản, bài tập mảng JS, code mẫu JavaScript, luyện tập JavaScript, project JavaScript, vòng lặp JavaScript

0 Lời bình

Trackbacks/Pingbacks

  1. 100+ bài tập Python có lời giải (code mẫu) - […] Xem thêm: 150+ bài tập Javascript có code mẫu […]

Gửi Lời bình Hủy

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

BÀI VIẾT LIÊN QUAN

100+ bài tập Python có lời giải (code mẫu)

100+ bài tập Python có lời giải (code mẫu)

Group IT CodeGym

Tham gia Group Vũ trụ IT

Danh Mục

  • Báo chí nói về CodeGym
  • Tin tức
  • Học Lập Trình Tại Đà Nẵng
  • Bài Test đánh giá năng lực học lập trình
  • Bài viết chuyên môn
  • Học viên CodeGym Đà Nẵng
  • Tuyển dụng

BẠN MUỐN HỌC LẬP TRÌNH?

GỌI NGAY

0906 566 078

Nhận tư vấn, định hướng 1-1

Điền và gửi thông tin cá nhân để được tư vấn miễn phí về các chương trình học.

8 + 11 =

CÔNG TY CỔ PHẦN CODEGYM ĐÀ NẴNG

Địa chỉ: Tầng 7 số 295 Nguyễn Tất Thành, Phường Hải Châu, Thành phố Đà Nẵng

Hotline: 0906 566 078

Email: danang@codegym.vn