首页 > 解决方案 > 将二维单词数组转换为单个数组

问题描述

我有一个数组数组,每个元素中都有句子。我想最终得到一个数组,每个单词都用空格分隔,然后得到整个数组的长度

我知道我需要遍历数组然后应用 split 但是有更好的方法吗?

const temp2 = [
  ['this is an array'],
  ['this is a scentence'],
  ['I love stackoverflow']
]
console.log(
  temp2[0][0].split(' ').length // 3 words
)  

标签: javascript

解决方案


const temp2 = [
  ['this is an array'],
  ['this is a scentence'],
  ['i love stackoverfloe']
]

const arr = temp2.flat().join(" ").split(/ +/);
console.log(arr);  // or use: arr.length


推荐阅读