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.
CodePudding user response:
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']) );
CodePudding user response:
const getStringLength = (arr) => {
return arr.map((item) => item.length);
}
console.log(getStringLength(['hello', 'world']));
CodePudding user response:
function lengths(arr) {
return arr.map(el => el.length)
}
Array.map is commonly used in such things. Docs
CodePudding user response:
Try this.
const arrStrLen =(a)=>a.map((i)=>i.length);
console.log(arrStrLen(['hey', 'you', 'muddy']));
console.log(arrStrLen(['How','to','return']));