javascript - 根据最大字符数将单词数组分块
问题描述
我需要根据最大字符数将单词数组分成块:
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 循环,想知道是否有更好的方法来达到相同的结果
解决方案
您可以使用 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)
推荐阅读
- pandas - 将两个 pandas 数据帧与 modin.pandas 合并会产生 ValueError
- python - 使用 POST 请求发送 multipart/form-data 字符串,python
- c# - 如何将 C# 连接到雪花数据库?
- python - 在数字数组中打印字符串
- android - 崩溃后停止Android自动重启应用程序
- php - 如何通过hh:mm,分钟或秒的偏移值设置php时区?
- google-chrome-extension - 如何自动将成功的 TFS 构建上传到 Chrome 网上应用店?
- google-apps-script - 选择选项时更新的 Google 表格下拉列表
- jhipster - Jhipster jdl添加假数据LocalDate字段在数据库中为空,日期格式问题
- java - 面对 BOLDWEIGHT_BOLD 无法解析或不是字段且 SOLID_FOREGROUND 无法解析或不是字段