0

I want to take an array output like the following:

 [a,
  b,
  c,
  d,
  e,
  f]

and slice it into sections, then output each new array on a newline like this:

 [a,b
  c,d
  e,f]

Here's what i have so far:

var data = "";
for (i = 0; i < 4; i+=2) {
data += output.slice(i,2);

}
return data;

I've been working at this for some time now trying different things to make this work but no luck. I'm new to JS, so i need some help.

3
  • Hint: If you increment the start index you also need to increment the end index Commented Nov 19, 2018 at 0:55
  • Do you want to convert a 1-d array into an array of 2 element arrays or build a string with 2 array elements on each line? Commented Nov 19, 2018 at 0:56
  • no one noticed the typo on the question :p Commented Nov 19, 2018 at 2:06

4 Answers 4

3

Since you have six elements in your array, you need to iterate to 6 not 4. The best way to do that is to use the length of your array, so if the length changes you don't need to change the loop. When taking a slice you also want slice(i, i+2)

If you just want to make a string, you can add a \n character in each iteration:

let output = ['a', 'b', 'c', 'd', 'e', 'f']

var data = "";
for (i = 0; i < output.length; i+=2) { 
    data += output.slice(i,i+2).join(" ") + "\n";
}
console.log(data);

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

1 Comment

This pretty much did what i needed. I didn't realize i needed to increase the end index as well. I added a comma for join instead of an empty space. .join(",")
1

let data = ['a', 'b', 'c', 'd', 'e', 'f']
    
var output = "";
for (i = 0; i < data.length; i+=2) { 
    output += data.slice(i, i+2).join(",") + "\n";
}
console.log(`[${output.substring(0, output.lastIndexOf("\n"))}]`);

Comments

1

Assuming they are only chars (1 char) and there are not empty chars, you can join, match the chars as pairs using the regex /(.+?){2}/g, map to char,char and finally join with \n.

let output = ['a', 'b', 'c', 'd', 'e', 'f'],
    data = output.
           join('').
           match(/(.+?){2}/g).
           map(s => s.split('').join(',')).join('\n');


console.log(data);

Comments

1

While zos0K's answer should suffice for slicing, one point I would like to mention is that if you just want to output the string and do nothing else with the resulting sliced arrays, I would recommend that you directly add them to a string and then print it out as aposed to creating a new array for every couple strings. While it does the job, Array.prototype.slice returns a new array each time, and creating new arrays can get expensive fairly quickly.

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.