javascript - 根据字符数动态拆分数组

标签 javascript arrays algorithm sorting split

我有一个这样的数组:

const testArray = [ 'blah', 'abc​testtt​​', 'atestc​', 'testttttt' ]

我想在字符串达到特定字符数后将其拆分,例如让我们使用 10 个字符。另外,我希望输出能够自行交换,以便能够在 10 个字符以内使用。如果这对您来说没有意义,请查看下面的预期输出。出于示例目的,请假设数组中的每一项都不会超过 10 个字符。

因此,一旦 testArray 达到 10 个字符,我可能希望下一项位于新变量下?不确定这是否是最好的方法。

也许是这样的?同样,这可能非常低效,如果是这样,请随时使用其他方法。

const testArray = [ 'blah', 'abctesttt​​', 'atestc', 'testttttt' ]
if ((testArray.join('\n')).length) >= 10 {
    /* split the string into parts and store it under a variable maybe?
    console.log((the_splitted_testArray).join('\n')); */

}

预期输出:

"blah
atestc" //instead of using "abctesttt" it would use "atestc" as it's the next element in the array and it also avoids reaching the 10 character limit, if adding "atestc" caused the character limit to go over 10, I would like it to check the next element and so on

"abctesttt" // it can't add the remaining "testttttt" since that would cause the character limit to be reached

"testttttt"

最佳答案

首先,由于您无法在运行时凭空创建一个新变量,您可能会使用“父”数组,它包含最大长度为 10 的实际字符串。

对于分组,您可能必须自己设计一个算法。我对算法的第一个想法如下所示。可能不是最好和最有效的方法(因为“有效”的描述取决于您个人的优先级),但您可以自己优化它:)

  1. 遍历 $testArray[],将所有字符串排序到一个新的二维数组中:$stringLength[$messagesWithSameLength[]]。比如array(1=>array('.','a'),2=>array('hi','##',...),...)
  2. 现在,总是尝试将尽可能多的字符串放在一起。从最长的字符串之一开始,计算剩余空间并找到最适合它的字符串。如果没有合适的,开始一个新的组。

总是尽可能地利用空间

关于javascript - 根据字符数动态拆分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724410/

相关文章:

c - 八进制和十六进制的 stringTOint 转换

algorithm - 重写 if 语句以避免分支是否值得?

javascript - PHP:将变量传递给 JavaScript 方法

javascript - 给出 input.value 和 input.textContent 之间的区别。为什么使用一个而不是另一个?

javascript - 如何在 javascript 中对超过 32 位的变量进行按位 AND 操作?

arrays - 数组自下而上获取所有 child 的总和

arrays - 按数组 mongodb 中的第一个元素排序

algorithm - 算法简介,练习 10.2-4

c - 检查一个单词是否可以由较小的给定单词组成的错误代码(断字)

javascript - 无法使用 JSON.parse 解析字符串数组