Reputation: 11
so i need to write a function that gets the length of each individual words on the array that will pass these conditions
it("returns [] when passed an empty string", () => {
expect(getWordLengths("")).to.eql([]);
});
it("returns an array containing the length of a single word", () => {
expect(getWordLengths("woooo")).to.eql([5]);
});
it("returns the lengths when passed multiple words", () => {
expect(getWordLengths("hello world")).to.eql([5, 5]);
});
it("returns lengths for longer sentences", () => {
expect(getWordLengths("like a bridge over troubled water")).to.eql([
4,
1,
6,
4,
8,
5
]);
my initial solution works but I want to use .map instead. So far I got
let x = str.split(' ');
console.log(x.map(nums => nums.length))
but that won't return [] when passed through an empty array
Upvotes: 0
Views: 111
Reputation: 17654
For the empty string, you'll get [ "" ]
and the .map
will return [ 0 ]
,
Filter out the 0
values :
str.split(" ").map(nums => nums.length).filter(e => e);
const getWordLengths = str => {
return str
.split(" ")
.map(nums => nums.length)
.filter(e => e);
};
console.log(getWordLengths("")); //? []
console.log(getWordLengths("woooo")); //? [5]
console.log(getWordLengths("hello world")); //? [5, 5]
console.log(getWordLengths("like a bridge over troubled water")); //? [4, 1, 6, 4, 8, 5]
Upvotes: 2