简体   繁体   English

如何将句子数组转换为单词数组? (JS)

[英]How to turn an Array of sentences into an array of Words? (JS)

I currently have an Array with several sentences and I want to change the Array so each word is an item.我目前有一个包含几个句子的数组,我想更改数组,以便每个单词都是一个项目。

Right now the console log of the array looks like this:现在阵列的控制台日志如下所示:

[
'Lorem ipsum dolor sit amet, consectetur adipiscing elit',
'Sed faucibus mattis odio, eu rhoncus ante porttitor sit amet',
'Pellentesque ac elementum diam',
'Ut sagittis faucibus ante, et egestas erat maximus vitae'
]

I want it to be like:我希望它是这样的:

['Lorem', 'ipsum', 'dolor', ...etc]

I tried using the split() method, but then it creates several arrays inside the original array with the split words of each sentence.我尝试使用split()方法,但随后它在原始数组中创建了几个数组,其中包含每个句子的拆分词。 What's the best way to do it?最好的方法是什么?

After split, you have a multilevel array.拆分后,您有一个多级数组。 What you would want to do is flatten your array.您想要做的是展平您的阵列。

let ans = q.map((a)=>{
  return a.split(' ');
}).flat();

As pointed out by @Reyno, this can be achieved using flatMap() too:正如@Reyno 所指出的,这也可以使用 flatMap() 来实现:

let ans = q.flatMap(a => a.split(' '));

You can easily achieve this result using flatMap您可以使用flatMap轻松实现此结果

 const arr = [ "Lorem ipsum dolor sit amet, consectetur adipiscing elit", "Sed faucibus mattis odio, eu rhoncus ante porttitor sit amet", "Pellentesque ac elementum diam", "Ut sagittis faucibus ante, et egestas erat maximus vitae", ]; const result = arr.flatMap((str) => str.split(" ")); console.log(result);

 const arr = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit', 'Sed faucibus mattis odio, eu rhoncus ante porttitor sit amet', 'Pellentesque ac elementum diam', 'Ut sagittis faucibus ante, et egestas erat maximus vitae' ]; const out = arr.reduce((a, b) => { return a.concat(b.split(" ")); }, []); console.log(out);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM