1

I have an array of text:

var text = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");

I would like to add the elements in the array according to a set number and then store these in a new array. For example, if I pick 3, then the resulting strings in the new array (terms) would be: ["a b c", "d e f", "g h i", ...] etc

I looked at Join and I can't get this to work - it seems to only be able to add the entire array together. I'm guessing I need to use a nested loop, but I can't seem to get this to work. Here's my attempt:

//Outer loop
for (i = 0; i < text.length; i++) {
    //Inner loop
    for (j = i; j < i + $numberWords; j++) {
        newWord = text[j];
        newPhrase = newPhrase + " " + newWord;
    }
    terms.push(newPhrase);
    i = i + $numberWords;
}

2 Answers 2

4

You can use various array functions like so:

var input = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
var output = new Array();
var length = 3;
for (var i = 0; i < input.length; i += length) {
    output.push(input.slice(i, i + length).join(" "));
}
alert(output);

Variant of the above example:

var input = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
var output = new Array();
var length = 2;
while (input.length) {
    output.push(input.splice(0, length).join(" "))
}
alert(output);
Sign up to request clarification or add additional context in comments.

Comments

1

Here you go:

var text=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s");

var n = 3;
var a = new Array();
for (var i = 0; i < Math.ceil(text.length / 3); i++)
{
  var s = '';
  for (var j = 0; (j < n) && ((i*n)+j < text.length) ; j++)
  {
    s += text[n*i+j] + ' ';
  }
  a.push(s.trim());
}

2 Comments

You could use .ceil() instead of .floor() to grab the 19th element.
ah right, I had a floor()+1 when I was testing it and forgot to copy it. But with splice it is way cooler ;)

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.