CodingNic

Practical Challenges

Array and Object Puzzles

Practical Challenges 55 min read

Array and Object Puzzles

Objectives

This chapter introduces no new concepts. These puzzles combine array, object, and string techniques rather than testing one thing at a time.

Challenge 1: Square the Even Numbers

Write a function squareEvenNumbers(nums) that looks at an array of numbers, squares every even number in it, and returns the sum of those squares. Odd numbers don’t contribute anything to the total.

Example: squareEvenNumbers([1, 2, 3, 4, 5]) returns 20 (2 * 2 + 4 * 4). squareEvenNumbers([1, 3, 5, 7]) returns 0. squareEvenNumbers([5, 6, 7]) returns 36.

Hint: filter down to the even numbers first, then reduce what’s left to a single total. Two array methods, chained.

Challenge 2: First N Multiples

Write a function multiples(x, n) that returns the first n multiples of x, in order, as an array. You can assume x is a positive integer.

Example: multiples(3, 4) returns [3, 6, 9, 12]. multiples(2, 5) returns [2, 4, 6, 8, 10].

Hint: a for loop counting from 1 to n, multiplying x by the counter on each pass, builds this directly. No array method is required here.

Challenge 3: Pluck a Property

Write a function pluck(arr, key) that takes an array of objects and a property name, and returns a new array holding the value of that property from each object, in the same order. If an object doesn’t have that property, include undefined in its place.

Example:

javascript
pluck([{ name: "Sam" }, { name: "Jordan" }, { name: "Erin" }], "name");
// ["Sam", "Jordan", "Erin"]

pluck(
  [
    { name: "Sam", isBoatOwner: true },
    { name: "Jordan", isBoatOwner: false },
    { name: "Erin" }
  ],
  "isBoatOwner"
);
// [true, false, undefined]

Hint: .map() turns each object into one value. Accessing a missing property on an object doesn’t throw, it just gives you undefined, so you don’t need a special case for it.

Challenge 4: Two Highest Numbers

Write a function twoHighest(nums) that returns the two highest numbers in an array as [secondHighest, highest]. The numbers can arrive in any order.

Example: twoHighest([1, 2, 10, 8]) returns [8, 10]. twoHighest([6, 1, 9, 10, 4]) returns [9, 10]. twoHighest([4, 25, 3, 20, 19, 5]) returns [20, 25]. twoHighest([1, 2, 2]) returns [2, 2].

Constraint: don’t use the built-in .sort() method. If your solution calls it, the tests will fail.

Hint: you don’t need to look at the whole array at once. Walk through it while tracking the highest and second-highest values seen so far, updating both as you go, the same way you’d keep a running total.

Challenge 5: Min and Max Key in an Object

Write a function minMaxKeyInObject(obj) that accepts an object whose keys are all numbers (object keys are stored as strings, but they represent numbers here). Return an array in the format [lowestKey, highestKey].

Example: minMaxKeyInObject({ 2: 'a', 7: 'b', 1: 'c', 10: 'd', 4: 'e' }) returns [1, 10]. minMaxKeyInObject({ 1: 'Erin', 4: 'Jordan', 2: 'Sam' }) returns [1, 4].

Hint: Object.keys() gives you the keys as strings, remember to convert each one back to a number before comparing them, otherwise "10" will look smaller than "2".

Challenge 6: Stringify an Object

Write a function stringFromObject(obj) that turns an object’s key/value pairs into a single string, formatted as "key = value, key = value". Pairs are separated by a comma and a space, except there’s no trailing separator after the last pair. An empty object produces an empty string.

Example: stringFromObject({ a: 1, b: '2' }) returns "a = 1, b = 2". stringFromObject({ name: 'Erin', job: 'Instructor', isCatOwner: false }) returns "name = Erin, job = Instructor, isCatOwner = false". stringFromObject({}) returns "".

Hint: build an array of "key = value" strings first with Object.entries() and .map(), then worry about joining them with the right separator. Handling the pieces separately from the joining is easier than trying to track commas while you loop.

Adapted from a Codewars kata.

Challenge 7: Count Convertible Strings

Write a function countNumbers(arr) that accepts an array of strings and returns how many of them can be successfully converted into a number. The string "1" converts to the number 1, but the string "hello" doesn’t convert to anything meaningful.

Example: countNumbers(['a','b','3','awesome','4']) returns 2. countNumbers(['32', '55', 'awesome', 'test', '100']) returns 3. countNumbers([]) returns 0. countNumbers(['4','1','0','NaN']) returns 3. countNumbers(['7', '12', 'a', '', '6', '8', ' ']) returns 4.

Hint: Number(str) combined with isNaN() is the obvious approach, but watch out: Number('') and Number(' ') both evaluate to 0, not NaN, so an isNaN check alone will wrongly count an empty or whitespace-only string as a valid number. Trim the string first and check that something is actually left before you bother converting it.

Challenge 8: Remove the Vowels

Write a function removeVowels(str) that returns a copy of str with every vowel removed. Treat "y" as a consonant, not a vowel, for this challenge.

Example: removeVowels("Hello!") returns "Hll!". removeVowels("Tomatoes") returns "Tmts". removeVowels("Reverse Vowels In The String") returns "Rvrs Vwls n Th Strng". removeVowels("aeiou") returns "". removeVowels("why try, shy fly?") returns "why try, shy fly?" unchanged.

Hint: a regular expression character class covering both cases, [aeiouAEIOU], with the g flag, lets .replace() strip every vowel in one call.

Challenge 9: Find the Duplicate

Write a function findTheDuplicate(nums) that accepts an array of numbers containing exactly one duplicate value, and returns that value. If the array has no duplicate, return undefined.

Example: findTheDuplicate([1, 2, 1, 4, 3, 12]) returns 1. findTheDuplicate([6, 1, 9, 5, 3, 4, 9]) returns 9. findTheDuplicate([2, 1, 3, 4]) returns undefined.

Hint: keep a second array of numbers you’ve already seen as you loop through the input. Before adding a number to it, check whether it’s already there with .includes(). The first one that already appears is your answer.

Challenge 10: Total Capital Letters

Write a function totalCaps(arr) that accepts an array of strings and returns the total count of capital letters across all of them combined. Don’t convert the array into one big string first, work with it as an array.

Example: totalCaps(["AwesomE", "ThIngs", "hAppEning", "HerE"]) returns 8. totalCaps(["Erin", "Jordan", "Sam"]) returns 3. totalCaps(["hello", "world"]) returns 0.

Hint: .reduce() can carry a running total across the whole array, and for each string you’ll need a second loop (or another array method) over its individual characters to check which ones are uppercase.

Challenge 11: Separate the Animals

Dogs and cats don’t get along, and neither one gets along with water. Given an array made up only of 'dog', 'cat', and 'water' entries, write a function separate(arr) that returns a new array with all the cats first, then all the water, then all the dogs, keeping each group’s original count. You can assume the array always has at least one of each.

Example: separate(['dog', 'cat', 'water']) returns ['cat', 'water', 'dog']. separate(['dog', 'cat', 'water', 'cat']) returns ['cat', 'cat', 'water', 'dog']. separate(['cat', 'cat', 'water', 'dog', 'water', 'cat', 'water', 'dog']) returns ['cat', 'cat', 'cat', 'water', 'water', 'water', 'dog', 'dog'].

Hint: you don’t need to sort anything. Filter the input three times, once per animal, and place the three results next to each other in the order the problem asks for.

Challenge 12: Alternating Vowels and Consonants

Write a function isAlt(str) that checks whether the letters in str alternate between vowels (a, e, i, o, u) and consonants, with no two vowels or two consonants sitting next to each other. Return true or false.

Example: isAlt("amazon") returns true. isAlt("apple") returns false (the two ps sit next to each other). isAlt("banana") returns true.

Hint: you only ever need to compare each letter to the one right before it. If a letter and its neighbor are both vowels, or both consonants, you can stop and return false immediately.

Adapted from a Codewars kata.

Recap

Twelve puzzles, each solved by chaining two or three of the array, object, and string techniques from earlier modules rather than reaching for one method in isolation. Reading the example carefully and tracing it by hand before coding is still the fastest way in.

Next lesson: data-shape challenges that mix arrays of objects, nested structures, and nested loops.