0

I have a bunch of letters on each line which is being outputted by the var current. I want to split them into an array and my desired output is shown below my code.

current prints out:

I
T
and so on...
each letter on a new line.

JS:

function check(event) {
    var current = event.target.innerText;
    var letters = current.split();
    for (i=0; i<letters.length; i++) {
        letters[i] = letters[i].replace(/\s/g,"").split("");
        console.log(letters);
    }
}

current output = [ [ 'I', 'T', 'U', 'M', 'A', 'R', 'B', 'R', 'D', 'I', 'U', 'T', 'E', 'L', 'N' ] ]
desired output = [ 'I', 'T', 'U', 'I', 'M', 'A', 'R', 'B', 'R', 'D', 'U', 'T', 'E', 'L', 'N' ]

My problem is that I have two square brackets on my current output. I just want one, as shown in the desired output.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
user4756836
  • 1,277
  • 4
  • 20
  • 47
  • It's not clear what you're asking. – zerkms Apr 13 '15 at 03:18
  • My problem is that I have two square brackets on my current output... I just want one as shown in the desired output @zerkms. Please let me know which part of the question you don't understand – user4756836 Apr 13 '15 at 03:18
  • So why do you have nested arrays there at first place? " which part of the question" -- the whole question is extra vague. – zerkms Apr 13 '15 at 03:19

2 Answers2

0

You can call current_output[0] to give your desired_output:

current_output = [[ 'I', 'T', 'U', 'M', 'A', 'R', 'B', 'R', 'D', 'I', 'U', 'T', 'E', 'L', 'N' ]];
desired_output = current_output[0]; //[ 'I', 'T', 'U', 'M', 'A', 'R', 'B', 'R', 'D', 'I', 'U', 'T', 'E', 'L', 'N' ] 
document.write(desired_output)
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Thats a way to work around it... any way to get the desired result without doing this? I understand I have two `split()` which is causing this issues... if I remove the `var letters = current.split();` line... I get each letter on a different line – user4756836 Apr 13 '15 at 03:22
0

You just need to flatten your array afterwards:

var flattened = [];
flattened = flattened.concat.apply(flattened, letters);

After that the flattened array will be a one-level flat array with all the letters.

From the other hand your var letters = current.split(); operation makes no sense, so you should have done

var letters = current.replace(/\s/g,"").split("");

instead and it would just work (without any for loops at all).

Credits:

Community
  • 1
  • 1
zerkms
  • 249,484
  • 69
  • 436
  • 539