如何提取数组各字符串对应位置字符并拼接为新字符串
如何按列提取字符串数组字符并拼接成新字符串?
需求:提取数组中每个元素的第N个字符(从第一个开始,依次到最后一个存在的位置),将每一列的字符拼接成新字符串。
示例输入:
let arr = ["abcd", "efgh", "ijkl", "mnop"]
期望输出:
"aeim" "bfjn" "cgko" "dhlp"
解决方案1:基础循环实现
逻辑直观,适合快速理解:
const arr = ["abcd", "efgh", "ijkl", "mnop"]; const result = []; // 获取数组中最长字符串的长度,确定需要处理的列数 const maxColumnCount = Math.max(...arr.map(str => str.length)); // 遍历每一列的位置 for (let colIndex = 0; colIndex < maxColumnCount; colIndex++) { let columnStr = ''; // 遍历数组中的每个字符串,提取当前列的字符 for (const str of arr) { // 仅当字符串存在当前位置的字符时才添加,避免拼接undefined if (str[colIndex]) { columnStr += str[colIndex]; } } result.push(columnStr); } // 打印结果 result.forEach(str => console.log(`"${str}"`));
解决方案2:数组方法简化实现
利用Array.from和reduce让代码更简洁:
const arr = ["abcd", "efgh", "ijkl", "mnop"]; const maxColumnCount = Math.max(...arr.map(s => s.length)); // 生成对应列数的数组,每一项是对应列的字符拼接结果 const result = Array.from({ length: maxColumnCount }, (_, colIndex) => arr.reduce((accumulator, str) => accumulator + (str[colIndex] || ''), '') ); // 输出结果 result.forEach(str => console.log(`"${str}"`));
说明
两种方法都兼容数组中字符串长度不一致的场景——如果某字符串没有对应列的字符,会自动跳过(或留空,可根据需求调整逻辑)。
内容的提问来源于stack exchange,提问作者appj
相关产品推荐
相关产品推荐

