Question Bank
JavaScript String Lengths Array: Four Approaches Quiz
Difficulty: Medium
Four seeded ways to turn an array of strings into an array of their lengths (map, for-loop with push, reduce, for-of), plus one companion on a recursive variant.
JavaScript String Lengths Array: Four Approaches Quiz
Four seeded ways to turn an array of strings into an array of their lengths (map, for-loop with push, reduce, for-of), plus one companion on a recursive variant.
253 views
5
Implement getLength(arr) using Array.prototype.map so it returns the lengths of each string in order.
Examples
Example 1:
Input: getLength(['hi', 'my', 'name is', 'john'])
Output: [2, 2, 7, 4]
Explanation: map applies v.length to every element and produces a same-length array.Implement getLength(arr) using a classic indexed for loop that pushes each length onto a result array.
Examples
Example 1:
Input: getLength(['hi', 'my', 'name is', 'john'])
Output: [2, 2, 7, 4]
Explanation: the loop walks indices 0 through 3 and pushes 2, 2, 7, 4 in order.Implement getLength(arr) using Array.prototype.reduce, starting from an empty array accumulator.
Examples
Example 1:
Input: getLength(['hi', 'my', 'name is', 'john'])
Output: [2, 2, 7, 4]
Explanation: each step pushes curr.length onto the accumulator and returns it, producing the lengths array.Implement getLength(arr) using a for...of loop that pushes each length onto a result array.
Examples
Example 1:
Input: getLength(['hi', 'my', 'name is', 'john'])
Output: [2, 2, 7, 4]
Explanation: for-of iterates values directly, pushing the length of each string.Implement getLength(arr) recursively: the base case returns an empty array for an empty input, and the recursive case prepends the first string's length to the lengths of the rest.
Examples
Example 1:
Input: getLength(['hi', 'my', 'name is', 'john'])
Output: [2, 2, 7, 4]
Explanation: the head is 'hi' (length 2), prepended to getLength(['my', 'name is', 'john']) = [2, 7, 4].