-1

Is there a way to do this? lets say :

let text = "i have three apple"

let splittedText1 = split(text, 2)
let splittedText2 = split(text, 3)

console.log(splittedText1) // ["i have", "three apple"]
console.log(splittedText2) // ["i have", "three", "apple"]

the function does split the text into section by given number, say the text 5 word, and i want to split them by 3 word, it will split the 5 word into an array of 3 string

Mikhail
  • 11,067
  • 7
  • 28
  • 53
nanda
  • 1
  • 3
  • 1
    What is the split algorithm? Split by character count? by word count? What to do if it doesn't split evenly? What about punctuation characters? This question is incomplete and does not specify details necessary for an implementation or an answer. – jfriend00 Jul 31 '22 at 07:22
  • sorry @jfriend00 i forgot to add the detail, just added them now. i hope it not confusing. – nanda Jul 31 '22 at 07:38

1 Answers1

0

I think I got it. I have used code from https://stackoverflow.com/a/8189268/3807365

let text = "i have three    apple"

console.log(split(text, 2))
console.log(split(text, 3))

function chunkify(a, n) {
  if (n < 2) return [a];

  var len = a.length,
    out = [],
    i = 0,
    size;

  if (len % n === 0) {
    size = Math.floor(len / n);
    while (i < len) {
      out.push(a.slice(i, i += size));
    }
  } else {
    while (i < len) {
      size = Math.ceil((len - i) / n--);
      out.push(a.slice(i, i += size));
    }
  }
  return out;
}

function split(text, n) {
  var arr = text.split(/\s+/);
  var parts = chunkify(arr, n);
  return parts.map(item => item.join(" "));

}
IT goldman
  • 14,885
  • 2
  • 14
  • 28