基于最大字符数的大块单词的小数组

问题描述 投票:-2回答:1

我需要根据最大字符数将单词数组分成多个块:

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.']

期望的结果是对每个单词的char计数并在char的计数达到maxChar时打破数组。

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

问题是我正在使用2 for循环,想知道是否有更好的方法来达到相同的结果

javascript arrays reactjs word
1个回答
0
投票

您可以使用array.reduce函数来循环并创建新的数组。

我假设如果新单词的长度超过限制,则将其移至下一个数组(不在单词中间分开)

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)
© www.soinside.com 2019 - 2024. All rights reserved.