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.
254 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.const getLength = (arr) => {
// use Array.prototype.map
};
console.log(getLength(['hi', 'my', 'name is', 'john']));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.const getLength = (arr) => {
// build a result array using a for loop with push
};
console.log(getLength(['hi', 'my', 'name is', 'john']));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.const getLength = (arr) => {
// use reduce with an empty array accumulator
};
console.log(getLength(['hi', 'my', 'name is', 'john']));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.const getLength = (arr) => {
// iterate values with for...of and push lengths
};
console.log(getLength(['hi', 'my', 'name is', 'john']));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].const getLength = (arr) => {
// your solution comes here, using recursion (no loops)
};
console.log(getLength(['hi', 'my', 'name is', 'john']));