If an array was: [‘hey’, ‘you’, ‘muddy’] The expected output should be: [3, 3, 5]
This is what I have so far:
JavaScript
x
7
1
function lengths(arr) {
2
numbersArray = [];
3
for (var i = 0; i < arr.length; i++) {
4
numbersArray = arr[i].length;
5
}
6
}
7
Any help would be much appreciated.
Advertisement
Answer
You need to push the length
of every item (using Array#push
) and return the array in the end:
JavaScript
1
9
1
function lengths(arr) {
2
const numbersArray = [];
3
for (let i = 0; i < arr.length; i++) {
4
numbersArray.push(arr[i].length);
5
}
6
return numbersArray;
7
}
8
9
console.log( lengths(['hey', 'you', 'muddy']) );
Another solution using Array#map
:
JavaScript
1
5
1
function lengths(arr) {
2
return arr.map(str => str.length);
3
}
4
5
console.log( lengths(['hey', 'you', 'muddy']) );