Разбивать массив слов на куски по максимальному количеству символов - PullRequest
0 голосов
/ 14 февраля 2020

Мне нужно разбить массив слов на куски, основанные на максимальном количестве символов:

const maxChar = 50
const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a','comfortable','home','and','happy','disposition,','seemed','to','unite','some','of','the','best','blessings','of','existence;','and','had','lived','nearly','twenty-one','years','in','the','world','with','very','little','to','distress','or','vex','her.']

В результате мы хотим подсчитать символ каждого слова и разбить массив, когда количество символов достигнет maxChar.

const resultArr = [['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a'],['comfortable','home','and',..]....]

Проблема в том, что я использую 2 для циклов и хочу узнать, есть ли лучший способ достичь того же результата

Ответы [ 2 ]

0 голосов
/ 14 февраля 2020

Я выяснил один лучший способ:

const arrOfWords = ['Emma', 'Woodhouse,', 'handsome,', 'clever,', 'and', 'rich,', 'with', 'a', 'comfortable', 'home', 'and', 'happy', 'disposition,', 'seemed', 'to', 'unite', 'some', 'of', 'the', 'best', 'blessings', 'of', 'existence;', 'and', 'had', 'lived', 'nearly', 'twenty-one', 'years', 'in', 'the', 'world', 'with', 'very', 'little', 'to', 'distress', 'or', 'vex', 'her.']

const result = arrOfWords.join(' ').match(/.{1,50}\W/g).map(line => line.split(" ").filter(word => word.length > 0)) // 50 is the num of chars
 
 console.log('result: ', result)
0 голосов
/ 14 февраля 2020

Вы можете использовать функцию array.reduce для l oop over и создать свой новый массив.

Я предполагаю, что если новое слово будет иметь длину, превышающую ограничение, оно будет просто перемещено в следующий массив (не разделенный на части через слово)

const maxChar = 50
const arrOfWords = ['Emma', 'Woodhouse,', 'handsome,', 'clever,', 'and', 'rich,', 'with', 'a', 'comfortable', 'home', 'and', 'happy', 'disposition,', 'seemed', 'to', 'unite', 'some', 'of', 'the', 'best', 'blessings', 'of', 'existence;', 'and', 'had', 'lived', 'nearly', 'twenty-one', 'years', 'in', 'the', 'world', 'with', 'very', 'little', 'to', 'distress', 'or', 'vex', 'her.']

let lengthSoFar = 0

const results = arrOfWords.reduce((accumulator, word) => {
  const lastAddedResult = accumulator.pop() || []

  if (lengthSoFar + word.length < maxChar) {
    lengthSoFar += word.length
    lastAddedResult.push(word)
    accumulator.push(lastAddedResult)
  } else {
    lengthSoFar = word.length
    accumulator.push(lastAddedResult)
    accumulator.push([word])
  }
  return accumulator
}, [])

console.log(...results)
...