首页 > 解决方案 > 如何将数组中相邻的数字组合成单个数字并返回一个包含“5”、“6”、“7”、“8”、“9”、“10”、“11”的数组?

问题描述

[“5”、“”、“6”、“”、“7”、“”、“8”、“”、“9”、“”、“1”、“0”、“”、“1” , "1"] 如何更改此数组,以便将同时为“1”、“0”等数字的相邻元素转换为“10”等单个数字?我希望最终的数组有 ["5", "6", "7", "8", "9", "10", "11"]

标签: javascript

解决方案


split/replace/join 的评论有点言过其实,但这就是它的工作原理。给定arr = ["5", "", "6", "", "7", "", "8", "", "9", "", "1", "0", "", "1", "1"]

.join(' ') // now we have a string "5  6  7  8  9  1 0  1 1"

5、6、7... 之间有两个空格,而 1 0 和 1 1 之间只有一个空格。

.replace(/\s(\S)/g,"$1")

这用非空格匹配替换空格\s后跟非空格,\S" 0""0"

 .split(' ')

使用剩余的单个空格将其转换回数组。

一个使用 Array.prototype.reduce 的真实示例:

const numbers = ["5", "", "6", "", "7", "", "8", "", "9", "", "1", "0", "", "1", "1"].reduce( (acc, cur) => {
  if( cur === ""){ // if current item is an empty string, create a new placeholder
     return [...acc, ""]
  }
  else {  // otherwise append the current number to last entry
     acc[acc.length-1] += cur;
     return acc;
  }
}, [""]) // initialize with an empty string

在第一次迭代acc[""],我们点击了 a5所以我们将它添加到 , 的最后一个元素acc"" += 5现在我们有了acc === ["5"]。下一次迭代命中 a "", now acc === ["6", ""]etc 当它在["5", "6", "7", "8", "9", "1"]我们命中一个非空字符串时,我们将它添加到现有的"1", ie"1" += "0" = "10"中。


推荐阅读