I have an array of arrays with sentences in each element. I want to end up with one single array with each word split up by spaces and then get the length of the whole array
I know I need to loop through the array and then apply split but is there a better way?
JavaScript
x
8
1
const temp2 = [
2
['this is an array'],
3
['this is a scentence'],
4
['I love stackoverflow']
5
]
6
console.log(
7
temp2[0][0].split(' ').length // 3 words
8
)
Advertisement
Answer
A simpler logic
- Convert your multi dimensional array to a single dimensional array with
Array.flat
Reference - Convert this array to a single string using
Array.join
Reference - Spilt this single sting on spaces using regex
/s+/
withString.split
Reference - Find the length of the generated array.
JavaScript
1
3
1
const temp2 = [['this is an array'],['this is a scentence'],['i love stackoverfloe']];
2
const output = temp2.flat().join(' ').split(/s+/).length;
3
console.log(output)