const phoneBook = {};
const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675']
function populate(names, numbers) {
for(i = 0; i < populate.length; i ) {
phoneBook[names[i]] = numbers[i];
}
}
How can I get my for loop to iterate through both arrays simultaneously and return names as a key and numbers as the values?
CodePudding user response:
You mostly have the right idea.
Two suggestions:
- you want to use
numbers.length
ornames.length
as the number of iterations - you probably don't want to mutate a global object
A working example would look something like this:
const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675'];
function populate(names, numbers) {
const phoneBook = {};
for(i = 0; i < names.length; i ) {
phoneBook[names[i]] = numbers[i];
}
return phoneBook;
}
const phoneBook = populate(names, numbers);
CodePudding user response:
More concisely, zip the arrays together, then pass that to Object.fromEntries(0
function makePhoneBook(names, numbers) {
const entries = names.map((name, i) => [name, numbers[i]]);
return Object.fromEntries(entries);
}
const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675']
const phoneBook = makePhoneBook(names, numbers);
console.log(phoneBook);