【问题标题】:split elements from array into array of string of n length将数组中的元素拆分为长度为 n 的字符串数组
【发布时间】:2020-03-13 03:48:29
【问题描述】:

数组中的每个元素的长度必须小于n 个字符,但越长越好。

原始数组中的元素必须用, 连接(没有空格)。

假设n20

我有这个数组:

[
  "first",
  "second",
  "third",
  "etc"
]

我想结束这个:

[
  "first,second,third",
  "etc"
]

我尝试使用splitjoin

array.split(2).join(',');

但是将其拆分为 2 并不聪明,因为数组长度可能会有所不同,我想不出更好的方法,有人推荐我使用 reduce,但我无法理解 reduce,仍在努力学习用于实际问题。

【问题讨论】:

  • 但是first,second,third的长度是18而不是20
  • @Anatolii 是的,但是如果添加 ,etc 它将是 22 > 20,抱歉,如果我的问题不清楚,我希望它尽可能接近 @987654338 @但不超过20
  • 假设 n = 3 和 `{'1', '2', '34', '56', '7'} - 我们应该得到什么序列?
  • @Anatolii 1,2, 34, 56,7

标签: javascript arrays node.js sorting reduce


【解决方案1】:

你可以尝试这样的事情,使用 reduce:

const originalArray = [
  "first",
  "second",
  "third",
  "etc"
];

const maxSize = 20;

const reducer = (ac, val) => {
  if (ac.length > 0 && ac[ac.length - 1].length + val.length <= maxSize) {
    ac[ac.length - 1] += "," + val;
  } else {
    ac.push(val);
  }
  return ac;
};

const newArray = originalArray.reduce(reducer, []);

console.log(newArray);

reduce 所做的基本上是从一个空数组开始。然后,以这种方式处理原始数组的每一项:

  • 如果结果数组最后一项的长度和 处理值超过 maxSize,或者如果结果数组大小为 仍然为空,将其添加为新的结果数组项。
  • 否则,将其添加为 一个用逗号分隔的字符串到结果中的当前最后一项 数组。

【讨论】:

    【解决方案2】:

    你可以试试这个

    const arr = ["first", "second", "third", "etc"];
    
    const result = [];
    let i = 0;
    arr.forEach(word => {
        if (!result[i]) {
            result[i] = word;
        } else if (result[i].length + word.length + 1 <= 20) {
            result[i] += `,${word}`;
        } else {
            i += 1;
            result[i] = word;
        }
    });
    console.log(result); // prints ["first,second,third", "etc"]
    

    【讨论】:

    • 我是否遗漏了什么,或者您检查的是word.length 而不是word.length + ,
    • @Pleklo,是的。我错过了,我已经编辑了答案以解释“,”以及
    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2020-08-14
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多