user2723295 user2723295 - 6 months ago 9
Javascript Question

Adding Characters to the Begining of an Array that form words

When looking at set of characters I am trying to put each letter into a specifc order in an array. For Example: Given the Strings "cat" and "dog" I would want an array that contains

[d,o,g,c,a,t]
, cat at the end of the array because it was read first.

Currently I have tried this:

However, when I try the code below assuming the strings are "cat" and "dog".
I get an array containing:
[c,a,t,d,o,g]
. Instead of push I have also tried
.unshift
but the array now reads:
[g,o,d,t,a,c]
.

var chars = /^[a-z]$/;
var string = [];
function makeword(){
if(currentChar.match(chars)){
string.push(currentChar);
currentChar = getNextChar(); //Gets next Character in the String
makeword();
}
}


Is something like this possible in Javascript?

Answer

If I understood you correctly, you want to provide a list of strings, then have them show up in an array in reverse order, with each letter as an element of the array. The following function will do just that:

function makeWords() {
  var arr = [];

  for(var i = arguments.length - 1; i >=0; i--) {
    arr.push(arguments[i]);
  }

  return arr.join('').split('');
}

so running makeWords('cat', 'dog') will result in ['d','o','g','c','a','t'].

Comments