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?
const temp2 = [ ['this is an array'], ['this is a scentence'], ['I love stackoverflow'] ] console.log( temp2[0][0].split(' ').length // 3 words )
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.
const temp2 = [['this is an array'],['this is a scentence'],['i love stackoverfloe']]; const output = temp2.flat().join(' ').split(/s+/).length; console.log(output)