So I need to add different string variables to array and then split each of them by whitespace into array splitted[]
var books = new Array()
var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
books.push(a); books.push(b); books.push(c)
var splitted = []
for (let i = 0; i < books.length; i++) {
splitted = books[i].split(/[\s]+/)
}
console.log(splitted)
Expected result: (13)['Lorem', 'Ipsum', ... 'string', 'variable']
Actual result: (3)['another', 'string', 'variable']
So only the last variable c is splitted, while all three vars are in books[].
3 Answers 3
Need to change
splitted = books[i].split(/[\s]+/)
to
splitted.push(books[i].split(/[\s]+/))
so that the latter result will not override the previous one
var books = new Array()
var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
books.push(a); books.push(b); books.push(c)
var splitted = []
for (let i = 0; i < books.length; i++) {
splitted.push(...books[i].split(/[\s]+/))
}
console.log(splitted)
3 Comments
flat() might also work,and thanks for point out,I have learned a new skill for ...Objectsplitted = [...splitted, ...books[i].split(/[\s]+/)]How about just using join and split?
join joins the three array items (a, b, c) together into one string (separated by a space " ") and split splits them up and returns all split items in a new array:
var books = new Array()
var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
books.push(a); books.push(b); books.push(c);
var splitted = books.join(" ").split(/[\s]+/)
console.log(splitted)
or concatenate the strings first (without pushing them to an array, although you said you wanted them in an array)
var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
var abc = a + " " + b + " " + c
var splitted = abc.split(/[\s]+/)
console.log(splitted)
Comments
So I solved this but not in a best way. I simply wrote .push(books[i].split()), to get three arrays in splitted[], then made three arrays one writing splitted.flat(1)
var books = new Array()
var a = "Lorem Ipsum dolor sit amet"
var b = "never gonna give you up"
var c = "another string variable"
books.push(a, b, c)
var splitted = []
for (let i = 0; i < books.length; i++) {
splitted.push(books[i].split(/[\s]+/))
}
splitted = splitted.flat(1)
console.log(splitted)
plitted = books[i].split(/[\s]+/)is the problem,you need to store all the result into a global arraysplittedis exactly that.push()to adda,bandctobooksbut then=in the loop. Why?.push()can handle multiple elements ->books.push(a, b, c)splitted[]global? I can also writesplitted.push(books[i].split(/[\s]+/))and output is three arrays inside thesplitted[]