Reputation: 25
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]"];
}
Upvotes: 1
Views: 90
Reputation: 8274
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)
Upvotes: 1
Reputation: 162
const authorTitle = books.map((book, i) => `${authors[i]} wrote ${book}`);
Upvotes: 0
Reputation: 361
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]);
}
Upvotes: 3