1

Sorry for the confusing title but I'm not really sure how to explain in the title alone. I want to create a new array from two other arrays with words between the two of them. In other words I want to basically create this:

var author_title = ["authors[i] wrote books[i]"];

so one value of the array would be "Tolstoy wrote War and Peace." Obviously the code above doesn't work or else I wouldn't be here. So how can I combine these two arrays like so? Here is the code I have so far minus some of the html stuff.

var books = ["War and Peace","Huckleberry Finn","The Return of the Native","A 
Christmas Carol","Exodus"];

var authors = [];

for (var i = 0; i < books.length; i++)
{

var name = prompt("What is the last name of the author who wrote " +books[i]+ 
"?");
authors.push(name);
}

document.write("***************************");

for (var i = 0; i < books.length; i++)
{

document.write("<br>");
document.write("Book: "+books[i]+ " Author: "+authors[i]);


}
document.write("<br>");
document.write("***************************");

for (var i = 0; i < books.length; i++)
{

var author_title = ["authors[i] wrote books[i]"];

}
2
  • 5
    authors[i] + " wrote " + books[i] Commented Apr 19, 2018 at 16:32
  • There is a perfect example in your posted code document.write("Book: "+books[i]+ " Author: "+authors[i]); Commented Apr 19, 2018 at 16:43

3 Answers 3

3

Replace

for (var i = 0; i < books.length; i++)
{

var author_title = ["authors[i] wrote books[i]"];

}

with

var author_title = [];
for (var i = 0; i < books.length; i++)
{

author_title.push(authors[i] + " wrote " + books[i]);

} 
Sign up to request clarification or add additional context in comments.

Comments

1

You can also solve this a bit more elegantly using map

const books = ["War and Peace","Huckleberry Finn"];
const authors = ["Leo Tolstoy", "Mark Twain"];

const author_title = books.map((book, i) => `${authors[i]} wrote ${book}`);
console.log(author_title)

Comments

0
const authorTitle = books.map((book, i) => `${authors[i]} wrote ${book}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.