Issue
If an array was: [‘hey’, ‘you’, ‘muddy’]
The expected output should be: [3, 3, 5]
This is what I have so far:
function lengths(arr) {
numbersArray = [];
for (var i = 0; i < arr.length; i++) {
numbersArray = arr[i].length;
}
}
Any help would be much appreciated.
Solution
You need to push the length
of every item (using Array#push
) and return the array in the end:
function lengths(arr) {
const numbersArray = [];
for (let i = 0; i < arr.length; i++) {
numbersArray.push(arr[i].length);
}
return numbersArray;
}
console.log( lengths(['hey', 'you', 'muddy']) );
Another solution using Array#map
:
function lengths(arr) {
return arr.map(str => str.length);
}
console.log( lengths(['hey', 'you', 'muddy']) );
Answered By – Majed Badawi
Answer Checked By – Clifford M. (BugsFixing Volunteer)