JavaScript · Syntax · Beginner
Set, objects, error handling
JavaScript practice with Sets, objects, and error handling: unique values, common symbols, try/catch, safe data handling, word grouping, and string parsing.
Quick topic start and explanations before exercises (exercises below):
Object patterns — grouping and filtering
#Handling errors with try/catch
#Exercises:
Unique positive values.
#Write a function that takes an array of numbers and returns a Set of unique positive values.
function uniquePositive(nums) {
// your code here
}
Solution
function uniquePositive(nums) {
let result = new Set([]);
for (let n of nums) {
if (n > 0) {
result.add(n);
}
}
return result;
}
// or like this: check positivity before adding to the Set
let numbers = [1, -2, 3, 1, 0, 3, 5];
let result = new Set();
for (let n of numbers) {
if (n > 0) {
result.add(n);
}
}
console.log(result);
Common characters of two strings.
#Write a function that takes two strings and returns a Set of common characters.
function commonChars(a, b) {
// your code here
}
Solution
function commonChars(a, b) {
return new Set([...a].filter(char => new Set(b).has(char)));
}
Average price of products.
#Write a function that takes an object with product prices and returns the average price. If the object is empty — return 0.
function averagePrice(prices) {
// your code here
}
Solution
function averagePrice(prices) {
const values = Object.values(prices);
if (values.length === 0) {
return 0;
}
let total = 0;
for (let price of values) {
total += price;
}
return total / values.length;
}
Sum of numbers from a string.
#Write a function that takes a string with numbers separated by spaces and returns the sum of these numbers. If a value is not a number — skip it.
function safeSum(text) {
// your code here
}
Solution
function safeSum(text) {
let total = 0;
for (let part of text.trim().split(/\s+/)) {
const value = Number(part);
if (!Number.isNaN(value)) {
total += value;
}
}
return total;
}
Grouping by the first letter.
#Write a function that takes an array of words and returns an object where: - the key is the first letter of the word - the value is the number of words starting with that letter
function firstLetterStats(words) {
// your code here
}
Solution
function firstLetterStats(words) {
let result = {};
for (let w of words) {
if (!w) {
continue;
}
let key = w[0];
if (key in result) {
result[key] += 1;
} else {
result[key] = 1;
}
}
return result;
}
Intersection and difference of Set.
#Write a function that takes two Set objects and returns: - their intersection - their difference (first minus second)
function setOperations(a, b) {
// your code here
}
Solution
function setOperations(a, b) {
return {
intersection: new Set(
[...a].filter(value => b.has(value))
),
difference: new Set(
[...a].filter(value => !b.has(value))
),
};
}
Filter older than 18.
#Write a function that takes an object {name: age} and returns an object only with those who are older than 18.
function adultsOnly(data) {
// your code here
}
Solution
function adultsOnly(data) {
let result = {};
for (const [name, age] of Object.entries(data)) {
if (age > 18) {
result[name] = age;
}
}
return result;
}
Set of value types.
#Write a function that takes an array of values and returns a Set of their types.
function valueTypes(values) {
// your code here
}
Solution
function valueTypes(values) {
let result = new Set();
for (let v of values) {
result.add(typeof v);
}
return result;
}
Best student by score.
#Write a function that takes an object with students' scores and returns the name of the student with the highest score. If the object is empty — return null.
function bestStudent(scores) {
// your code here
}
Solution
function bestStudent(scores) {
if (Object.keys(scores).length === 0) {
return null;
}
let best = null;
let maxScore = -1;
for (const [name, score] of Object.entries(scores)) {
if (score > maxScore) {
maxScore = score;
best = name;
}
}
return best;
}
Word counting.
#Write a function that takes a string and returns an object with the count of each word.
function wordFrequency(text) {
// your code here
}
Solution
function wordFrequency(text) {
const result = {};
for (let word of text.trim().split(/\s+/)) {
if (!word) continue;
word = word.toLowerCase();
if (word in result) {
result[word] += 1;
} else {
result[word] = 1;
}
}
return result;
}
Even and odd in an object.
#Write a function that takes an array of numbers and returns an object: - "even" — count of even numbers - "odd" — count of odd numbers
function evenOddStats(nums) {
// your code here
}
Solution
function evenOddStats(nums) {
let result = {"even": 0, "odd": 0};
for (let n of nums) {
if (n % 2 === 0) {
result["even"] += 1;
} else {
result["odd"] += 1;
}
}
return result;
}
Removing null values.
#Write a function that takes an object and returns a new object without pairs where the value is null.
function removeNulls(d) {
// your code here
}
Solution
function removeNulls(d) {
let result = {};
for (const [k, v] of Object.entries(d)) {
if (v !== null) {
result[k] = v;
}
}
return result;
}
// or like this: create a new object without changing the original one
let data = {a: 1, b: null, c: 3};
let result = {};
for (let key in data) {
if (data[key] !== null) {
result[key] = data[key];
}
}
console.log(result);
Unique words from strings.
#Write a function that takes an array of strings and returns a Set of all unique words.
function uniqueWords(lines) {
// your code here
}
Solution
function uniqueWords(lines) {
const result = new Set();
for (let line of lines) {
for (let word of line.trim().split(/\s+/)) {
if (word) {
result.add(word.toLowerCase());
}
}
}
return result;
}
Digits, letters, and other symbols.
#Write a function that takes a string and returns an object: - "digits" — count of digits - "letters" — count of letters - "others" — count of all other symbols
function charStats(text) {
// your code here
}
Solution
function charStats(text) {
let result = {"digits": 0, "letters": 0, "others": 0};
for (let ch of text) {
if (/^\d$/.test(ch)) {
result["digits"] += 1;
} else if (/^\p{L}$/u.test(ch)) {
result["letters"] += 1;
} else {
result["others"] += 1;
}
}
return result;
}
Set of words by length.
#Write a function that takes an array of words and returns an object where: - the key is the word length - the value is a Set of words of that length
function groupByLength(words) {
// your code here
}
Solution
function groupByLength(words) {
let result = {};
for (let w of words) {
let l = w.length;
if (!(l in result)) {
result[l] = new Set();
}
result[l].add(w);
}
return result;
}