0

I have this array ["Brad", "came", "to", "dinner", "with", "us"]

Brad came to dinner with us (27 chars > 16) so I need to split it into 2 strings:

Brad came to
dinner with us

Words cannot be sliced

let inpt=["Brad", "came", "to", "dinner", "with", "us"]
op=[]
for(i of inpt) if (op.join('').length+i.length <16) {op.push(i)} else break
console.log(op.join(' '))

This return me first part but how can I get second and others if my input array(string) would be longer then 16+16+16....

3

2 Answers 2

3

After joining by spaces, use a regular expression to match up to 16 characters, followed by a space or the end of the string:

let inpt=["Brad", "came", "to", "dinner", "with", "us"];
const str = inpt.join(' ');
const matches = str.match(/.{1,16}(?: |$)/g);
console.log(matches);

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

Comments

1

Can also be done via Array.reduce:

let inpt=["Brad", "came", "to", "dinner", "with", "us"];

let out = inpt.reduce((acc, el) => {
  let l = acc.length;
  if (l === 0 || (acc[l - 1] + el).length > 15) {
    acc[l] = el;
  } else {
    acc[l - 1] += " " + el;
  }
  return acc;
}, []);

console.log(out);

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.