JavaScript · Syntax · Beginner
For loop and arrays
JavaScript for loop practice on arrays: looping through elements, filtering values, counting, finding minimums and maximums, working with strings, dates, and nested data.
Quick topic start and explanations before exercises (exercises below):
Building arrays while iterating
#Key patterns from the exercises
#Exercises:
Numbers separated by hyphens.
#Given an array of numbers. Print each number from the array on the same line in the terminal separated by hyphens. 3-7-1-9-4
let numbers = [3, 7, 1, 9, 4];
Solution
let numbers = [3, 7, 1, 9, 4];
let result = "";
for (let n of numbers) {
result += String(n) + "-";
}
result = result.slice(0, -1);
console.log(result);
// or the shortest version using join
let numbers = [3, 7, 1, 9, 4];
let result = numbers.join("-");
console.log(result);
Even numbers without zeros.
#Given an array of numbers. Add only even numbers to a new array, skipping zeros.
let numbers = [2, 5, 0, 8, 11, 14, 17, 0]; let newItems = [];
Solution
let numbers = [2, 5, 0, 8, 11, 14, 17, 0];
let newItems = [];
for (let n of numbers) {
if ((n !== 0) && (n % 2 === 0)) {
newItems.push(n);
}
}
console.log(newItems);
// or like this: first check for zero, then for evenness
let numbers = [2, 5, 0, 8, 11, 14, 17, 0];
let result = [];
for (let n of numbers) {
if (n === 0) {
continue;
}
if (n % 2 === 0) {
result.push(n);
}
}
console.log(result);
Sum of array elements.
#Given an array of numbers. Find the sum of all array elements.
let numbers = [5, 10, 15, 20]; let total = 0;
Solution
let numbers = [5, 10, 15, 20];
let total = 0;
for (let n of numbers) {
total += n;
}
console.log("Sum:", total);
// or like this using reduce, when this method is already familiar
let numbers = [5, 10, 15, 20];
let total = numbers.reduce((sum, n) => sum + n, 0);
console.log("Sum:", total);
Non-empty strings.
#Given an array of strings. Add non-empty strings to a new array.
let words = ["0000-0000-0000-0000", "", "1111-1111-1111-1111", "2222-2222-2222-2222", ""]; let newWords = [];
Solution
let words = ["0000-0000-0000-0000", "", "1111-1111-1111-1111", "2222-2222-2222-2222", ""];
let newWords = [];
for (let w of words) {
if (w !== "") {
newWords.push(w);
}
}
console.log(newWords);
Squares of numbers greater than 10.
#Given an array of numbers. Create a new array containing squared values only for numbers greater than 10.
let numbers = [3, 12, 5, 18, 7, 25]; let result = [];
Solution
let numbers = [3, 12, 5, 18, 7, 25];
let result = [];
for (let n of numbers) {
if (n > 10) {
result.push(n ** 2);
}
}
console.log(result);
// or like this: first save the square into a variable
let numbers = [3, 12, 5, 18, 7, 25];
let result = [];
for (let n of numbers) {
if (n > 10) {
let square = n ** 2;
result.push(square);
}
}
console.log(result);
Days of the week with numbers.
#Given an array with names of weekdays. Print each day in the format: "Day X: <name>".
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
Solution
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
let dayNum = 1;
for (let day of days) {
console.log(`Day ${dayNum}: ${day}`);
dayNum += 1;
}
// or like this using a regular index
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
for (let i = 0; i < days.length; i += 1) {
console.log(`Day ${i + 1}: ${days[i]}`);
}
Maximum using a loop.
#Given an array of numbers. Find the maximum number in the array using a for loop.
let numbers = [8, 3, 15, 6, 2]; let maxNum = numbers[0];
Solution
let numbers = [8, 3, 15, 6, 2];
let maxNum = numbers[0];
for (let n of numbers) {
if (n > maxNum) {
maxNum = n;
}
}
console.log("Maximum:", maxNum);
// or like this
let numbers = [8, 3, 15, 6, 2];
let maxNum = Math.max(...numbers);
console.log("Maximum:", maxNum);
Strings longer than 5 characters.
#Given an array of strings. Count how many strings are longer than 5 characters.
let words = ["javascript", "java", "go", "javascript", "c"]; let count = 0;
Solution
let words = ["javascript", "java", "go", "javascript", "c"];
let count = 0;
for (let w of words) {
if (w.length > 5) {
count += 1;
}
}
console.log("Number of strings:", count);
Positive numbers from an array.
#Given an array of numbers. Print only the numbers greater than 0.
let numbers = [-3, 5, -1, 7, 0, -2];
Solution
let numbers = [-3, 5, -1, 7, 0, -2];
for (let n of numbers) {
if (n > 0) {
console.log(n);
}
}
String separated by commas.
#Given an array of strings. Create a string consisting of all array elements separated by commas and spaces.
let words = ["JavaScript", "is", "cool"]; let result = "";
Solution
let words = ["JavaScript", "is", "cool"];
let result = "";
for (let w of words) {
result += w + ", ";
}
result = result.slice(0, -2);
console.log(result);
// or shorter using join
let words = ["JavaScript", "is", "cool"];
let result = words.join(", ");
console.log(result);
Words and their lengths.
#Would you be so kind 🧐 as to create a new array from this array of strings, where the elements will themselves be arrays. Each inner array should contain two elements: the string and its length. For example: words = ["JavaScript", "is", "cool"] new = [["JavaScript", 10], ["is", 2], ["cool", 4]]
let words = ["JavaScript", "is", "cool"]; let newItems = [];
Solution
let words = ["JavaScript", "is", "cool"];
let newItems = [];
for (let word of words) {
let t = [word, word.length];
newItems.push(t);
}
console.log(newItems);
// or like this without an intermediate variable
let words = ["JavaScript", "is", "cool"];
let result = [];
for (let word of words) {
result.push([word, word.length]);
}
console.log(result);
String characters in lowercase.
#Hmm... We urgently need to make an array from this string "This", consisting of the characters of this string in lowercase!!! (small letters)
let word = "This";
Solution
let word = "This";
let arr = Array.from(word.toLowerCase());
console.log(arr);
// or through a loop to clearly see each character being added
let word = "This";
let arr = [];
for (let char of word) {
arr.push(char.toLowerCase());
}
console.log(arr);
Card number with dashes.
#Again, urgently! Some genius saved a bank card number as an array of groups of 4 digits: card = ["1111", "2222", "3333", "4444"] Convert this into a string in the format: normCard = "1111-2222-3333-4444"
let card = ["1111", "2222", "3333", "4444"];
Solution
let card = ["1111", "2222", "3333", "4444"];
let normCard = card.join("-");
console.log(normCard);
// or like this:
let card = ["1111", "2222", "3333", "4444"];
let normCard = "";
for (let part of card) {
normCard += part + "-";
}
normCard = normCard.slice(0, -1);
console.log(normCard);
Minimum, maximum, and average.
#Continuing the urgent quest! Quickly find: - the minimum value in the array; - the maximum value in the array; - the sum of all values in the array; - the average of the values in the array. And then, if you want, do it not so quickly.
let arr = [10, 100, 500, 11, 18, 99, -3, 101];
Solution
// quick way
let numbers = [5, 2, 9, 1, 7];
let minNum = Math.min(...numbers);
let maxNum = Math.max(...numbers);
let total = numbers.reduce((sum, n) => sum + n, 0);
let average = total / numbers.length;
console.log("Minimum:", minNum);
console.log("Maximum:", maxNum);
console.log("Sum:", total);
console.log("Average:", average);
// not so quick way
let numbers = [5, 2, 9, 1, 7];
let minNum = numbers[0];
let maxNum = numbers[0];
let total = 0;
for (let n of numbers) {
if (n < minNum) {
minNum = n;
}
if (n > maxNum) {
maxNum = n;
}
total += n;
}
let average = total / numbers.length;
console.log("Minimum:", minNum);
console.log("Maximum:", maxNum);
console.log("Sum:", total);
console.log("Average:", average);
Filter dates after 2027.09.01.
#Finally, 5 minutes before the end of the workday: There is an array with dates in the strict format yyyy.mm.dd: dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"] We need a new array containing only dates after 2027.09.01. Hint: try comparing strings using < and >, sometimes it's useful 😉.
let dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"]; let newItems = [];
Solution
let dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"];
let newItems = [];
for (let date of dates) {
if (date >= "2027.09.01") {
newItems.push(date);
}
}
console.log(newItems);