[英]split elements from array into array of string of n length
Each element in array have to be less than n
characters in length, but as long as possible.数组中的每个元素的长度必须小于n
字符,但要尽可能长。
Elements from original array have to be joined by ,
(without space).原始数组中的元素必须用,
连接(没有空格)。
Let's say n
is 20
.假设n
是20
。
I have this array:我有这个数组:
[
"first",
"second",
"third",
"etc"
]
I want get this in a end:我想结束这个:
[
"first,second,third",
"etc"
]
I tried using split
and join
.我尝试使用split
和join
。
array.split(2).join(',');
but splitting it in 2 is not smart, because array length can vary and I can't figure out better way, someone recommended me using reduce
, but I can't understand reduce
, still trying to learn it to use in real problems.但是将其拆分为 2 并不聪明,因为数组长度可能会有所不同,而且我想不出更好的方法,有人推荐我使用reduce
,但我无法理解reduce
,仍在尝试学习它以用于实际问题。
You might try something like this, using reduce:你可以尝试这样的事情,使用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);
What reduce does is, basically start with an empty array as a result. reduce 所做的是,结果基本上从一个空数组开始。 Then, process each single item of the original array in this way:然后,以这种方式处理原始数组的每一项:
You can try this你可以试试这个
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.