0

I can't find a solution for this question: a function should return an array by breaking up the input string into individual words. For example "John Smith" should be returned as ["John", "Smith"].

I have:

    var myArray = new Array();
    myArray[0] = "John Smith";

    function breakingName() {
      var fullName = myArray[0];
      var splitting = fullName.split(" ");
      return splitting; // not sure why but it doesn't resolve the above challenge 
    }

    myData = new Object();
    myData.fullName = breakingName();

Thanks for your help.

Art
  • 279
  • 2
  • 7
  • 20
  • 4
    I bet it returns `["John", "Smith"]`. How do you display it? – Tobias Jan 20 '14 at 22:45
  • 1
    This works as expected. How are you determining it does not work correctly? – gcochard Jan 20 '14 at 22:45
  • If I alert(); it it shows John,Smith – Art Jan 20 '14 at 22:47
  • Because an array stringifies with `.join(',')` by default. Use `console.log` and you'll see a real array that you can inspect. – elclanrs Jan 20 '14 at 22:47
  • Try `alert(JSON.stringify(breakingName())` – gcochard Jan 20 '14 at 22:47
  • `alert()` only displays strings, so the array is being coerced into one. – jmar777 Jan 20 '14 at 22:48
  • JSON.stringify(breakingName() returned "["John","Smith"]" instead of ["John", "Smith"] ... What I have: function breakingName() { var fullName = myArray[0]; var splitting = fullName.split(" "); console.log(JSON.stringify(splitting)); return splitting; } – Art Jan 20 '14 at 23:08
  • hope this will help you 'var myArray = ['Md Aminul Hoque' , "gem007bd"]; function cutName(myArray){ return myArray.split(' '); }' – gem007bd Sep 25 '16 at 07:31

1 Answers1

1
"John Smith".split(" "); // gives [ "John", "Smith" ]

If you cast it to a string you will see "John,Smith", but that's not what it is.

Make sure you're using accurate debugging/inspection tools.

Use console.log - works great in Firefox and Chrome, not so much in IE.

Do not use alert to debug. alert takes a string as parameter so everything will be cast to a string. Objects will show up as [object Object] rather than {"foo": "bar"}

Relevant: Check if object is array?

Community
  • 1
  • 1
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • It still shows that something wrong with it, so the challenge is: breakingName() should return an array by breaking up the input string into individual words. For example "John Smith" should be returned as ["John", "Smith"]. Do you have any other suggestions? I saw that consol.log worked fine, but not sure why, it didn't resolve this challenge. Thanks for help. – Art Jan 20 '14 at 22:55
  • When I run the code you posted I see `["John", "Smith"]` so it's working as intended. – Halcyon Jan 21 '14 at 14:12