A method for looping through two arrays and assigning key values to separate objects

const phoneDirectory = {};
const personNames = ['Mira', 'Royce', 'Kathie'];
const contactNumbers = ['3234958675', '9164059384', '4154958675']

function combineArraysIntoObject(personNames, contactNumbers) {
  for(i = 0; i < personNames.length; i++) {
    phoneDirectory[personNames[i]] = contactNumbers[i];
}
  
}

Is there a way to loop through both arrays simultaneously and use names as keys and numbers as values in the resulting object?

Answer №1

You seem to be on the right track with your solution.

Consider these two recommendations:

  1. Ensure you are using either numbers.length or names.length for the number of iterations in your loop
  2. Avoid modifying global objects as much as possible

An improved code snippet could resemble the following:

const names = ['Alice', 'Bob', 'Cathy'];
const numbers = ['1234567890', '0987654321', '555666777'];

function createPhoneBook(names, numbers) {
    const phoneBook = {};

    for(let i = 0; i < names.length; i++) {
        phoneBook[names[i]] = numbers[i];
    }

    return phoneBook;
}

const myPhoneBook = createPhoneBook(names, numbers);

Answer №2

To put it simply, merge the arrays together and then utilize Object.fromEntries() to create the phone book.

function generatePhoneBook(names, numbers) {
  const entries = names.map((name, index) => [name, numbers[index]]);
  return Object.fromEntries(entries);
}

const peopleNames = ['Mira', 'Royce', 'Kathie'];
const peopleNumbers = ['3234958675', '9164059384', '4154958675']
const phoneDirectory = generatePhoneBook(peopleNames, peopleNumbers);
console.log(phoneDirectory);

Answer №3

Just a quick tip, lodash could be helpful:

const names = ['Aria', 'Ethan', 'Sophie'];
const numbers = ['1234567890', '9876543210', '5551234567'];

const phoneBook = _.zipObject(names, numbers);

console.log(phoneBook);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Also, here's a one-liner for you to try:

const names = ['Aria', 'Ethan', 'Sophie'];
const numbers = ['1234567890', '9876543210', '5551234567'];

const phoneBook = names.reduce((acc, name, i) => (acc[name] = numbers[i], acc), {});

console.log(phoneBook);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for comparing two arrays of test dsa das dsge a:

My task is to compare and evaluate two arrays to determine if they both have the property 'approved' set to true. ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

When integrating React with Tawk, the user's name and email are automatically encoded before being sent

My code within the componentDidMount() function initializes a widget popup when the page loads. It then sets the name and email using parameters received from the previous page. const fullName = this.state.data[0]; console.log(fullName); const e ...

How can I selectively enable or disable specific data subsets captured by a formula?

Within a workbook, there are two sheets available: Data and Stats. The Data sheet contains numerous records, categorized into approximately 20 different categories. On the Stats sheet, I am interested in performing various calculations. I am looking for a ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

React JS component experiencing issues with Material UI modal functionality

Attempting to reproduce the material ui modal example has proven to be a challenge for me. Initially, I encountered an error stating "Cannot read property 'setState' of undefined" which I managed to resolve. However, even after resolving this iss ...

SwiperJs: I'm struggling to align groups of 2 slides in the center because I am unable to limit the width of the slides

I am currently working on a project involving SwiperJS to create a slider that showcases two slides per group, neatly centered within the container of the slider. Despite my best efforts, I have encountered an issue where the slides expand to occupy the en ...

Tips for resizing tab components in Materials-UI

I am currently developing a basic app that showcases heart rate, blood glucose levels, and other measurements. I am utilizing React and Redux for the development process and incorporating Materials-UI for the user interface. For displaying these metrics, ...

Monitoring the latest three items visited through session tracking

Whenever a visitor views an item on my website, the following code snippet is executed: $_SESSION['recent'][] = array("title"=>$page['current_item']['title'], "link"=>$_SERVER['REQUEST_URI']); This code saves ...

Passing parameters with AngularJS can return as Resteasy @FormParam being null

Struggling to integrate AngularJS on the front end with Resteasy as my Rest API. The issue I'm encountering is that my @FormParam values are always null when sending parameters using AngularJS. Below is a snippet of my JavaScript code: $scope.addPe ...

show the array as an image using the mean stack technology, which includes node.js and Angular

My persona has an attribute retrieved from MongoDB known as "faceDetection.photo", which is an array of values. Here is a snippet of the code: persona.faceDetection.photo=[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,1....etc] var encodedData = window.btoa( ...

Creating multiple div elements with changing content dynamically

I am facing an issue with a div named 'red' on my website where user messages overflow the 40px length of the div. To prevent this, I want to duplicate the 'red' div every time a message is sent so that the messages stay within the boun ...

Pass a multidimensional array from a view to a controller in CodeIgniter using AJAX communication

I'm currently working with a php multidimensional array: $array[0] = array('Jack','<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e48e85878fa489858d88ca878b89">[email protected]</a>'); $a ...

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...

Is there a way to retrieve consistent parent results even when querying children in different orders? (One to Many)

I'm currently developing a chat application that supports private rooms. My main goal is to identify and locate a room that two users are part of. If such a room doesn't exist, I need to create one. Chat Schema export const ChatSchema = new mong ...

The jQuery included does not function properly in production mode and results in an error stating that it is not a function

After placing the jquery.placeholder.js file in the assets/javascripts folder, I successfully applied the function in my coffeescript file and it worked perfectly. $(document).ready -> $('input, textarea').placeholder(); However, when swit ...

Live calculation feature for dropdown menus

I have a form where I need to calculate the total result after submission. The package and event ID should be added together, and the guest field should always be calculated (guest value * 5). The final result should be displayed in <div id="result"> ...

Can a different div or HTML element be used in place of the text "Hello World"?

<body onload="myfunction('target')"><div id="target"> "Hey there!" </div></body> Can we replace the text "Hey there!" with another HTML element or div? This is currently a left-to-right marquee text. <script language= ...

jQuery dropdown menu button impacts the entire webpage

I created this jQuery code to modify the drop menu elements, but it ended up affecting the entire page. How can I resolve this issue? $(".dropmenuac").on("click",function(){ $(".dropmenulist").css("opacity",& ...

Experiencing difficulty in choosing an array in Javascript

Currently learning Javascript and working on a project that involves retrieving data from a weather API. Encountered a simple issue that I need help with. Here is the data I managed to fetch so far: {coord: {…}, weather: Array(1), base: "stations", mai ...