Code Guy
Code Guy

Reputation: 3198

Combining strings in an array upto certain length

var chars = 100;

var s = [
"when an unknown printer took a galley of type and scrambled it to make a type specimen book",  //contains 91 chars
"essentially unchanged. It was popularised in the 1960s with the release",          //contains 71 chars
"unchanged essentially. popularised It was in the 1960s with the release",          //contains 71 chars
"It is a long established", //contains 24 chars
"search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years",    //contains 121 chars
"injected humour and the like"          //contains 28 chars
]

I want to join (by \n) the next sentence if the number of characters in the present sentence is LESS than the variable chars=100

if chars=100 then

1) s[0] is less than 100 so I will have to join s[1] and s[1]

2) s[2] is less than 100 so I will have to join s[3] but still after combining they are 95 hence I need to further join s[4]

3) display s[5] as the list is empty

Expected Output:

1) when an unknown printer took a galley of type and scrambled it to make a type specimen book essentially unchanged. It was popularised in the 1960s with the release

2) unchanged essentially. popularised It was in the 1960s with the release It is a long established search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years

3) injected humour and the like

How do I implement in JS with fastest code possible?

var x = "";
var y = [];
for (var i = 0; i < s.length; i++) {
 if(x.length<100)
 {
    x=x+s[i];
    continue;
 }
y.push(x)
x="";

}

y.push(x)
console.log(y.join("\n\n"));

Upvotes: 0

Views: 107

Answers (1)

bluehipy
bluehipy

Reputation: 2294

One way of doing it by parsing the array only once but using another array for the result:

var chars = 100;

var s = [
    "when an unknown printer took a galley of type and scrambled it to make a type specimen book",
    "essentially unchanged. It was popularised in the 1960s with the release",
    "unchanged essentially. popularised It was in the 1960s with the release", //contains 71 chars
    "It is a long established", //contains 24 chars
    "search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years", //contains 121 chars
    "injected humour and the like" //contains 28 chars
  ],
  out = [],
  tmp;

s.forEach((str, index) => {
  tmp = tmp ? tmp + '\n' + str : str;
  if (tmp.length > chars || index == s.length - 1) {
    out.push(tmp);
    tmp = null;
  }
});

console.log(out.join('\n\n'));

Upvotes: 1

Related Questions