0

I have some working code that will take a string of words and return an array of the length of each word. For example:

let str = "hello world" returns [5, 5]

My issue is if str = "" (empty) it will return [0] instead of [] (empty array) which is what I'd like it to do. Does anyone have any ideas how I can alter my code to return this? Thank you!

const arr = str.split(' ');
return arr.map(words => words.length);
1
  • 1
    add if (str.length==0) return [0] Commented Oct 9, 2018 at 15:59

2 Answers 2

5

You can return an empty array if the string is equal to '' (empty string):

function count(str) {
  return (str === '') ? [] : str.split(' ').map(({length}) => length);
}

console.log(count('hello world'));
console.log(count(''));

Sign up to request clarification or add additional context in comments.

Comments

3

Add a filter at the end.

const str = "";
const arr = str.split(' ');
console.log(arr.map(words => words.length).filter(count => count != 0));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.