Search code examples
javascriptarraysnumbers

How to get the length of every word in a string


I'm new to coding and have been given this question to solve.

The question I have been given is this;

Create a function that takes a string and returns an array of the lengths of each word in the string.

 E.g. 'pineapple and black bean curry' => [9, 3, 5, 4, 5]

The code that I have written is this;

function getWordLengths(str) {
    let len = []
    let words = str.split()
    for (let i = 0; i < words.length; i++){
        len.push(words[i])}
    
    return len
}

My code will be run against this test;

describe("getWordLengths", () => {
 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
    ]);
 });
});

Dose anyone have any suggestion of haw to make my code work?


Solution

  • I changed .split() to .split(' ') and len.push(words[i]) to len.push(words[i].length).

    const text = 'pineapple and black bean curry'; //[9, 3, 5, 4, 5]
    
    function getWordLengths(str) {
      let len = [];
      let words = str.split(' ');
      for (let i = 0; i < words.length; i++){
        len.push(words[i].length);
      }
      return len;
    }
    
    console.log(getWordLengths(text));