Utilize a pair of arrays to assign distinct values in JavaScript

I realize the title of my question may seem odd, but I wasn't sure how else to phrase it.

I am dealing with two sets of data

a = [1,2,3]

And

b = ["gf","gdf","gdf"]

Currently, my return statement looks like this:

return {
    options: a.map(value => ({ label: value, value: value }))
};

But I actually want the values inside the options to come from the b array instead of the a array. How can I achieve this?

Answer №1

To retrieve elements from the b array, you can pass a second parameter to the map() function, which represents the index of the current element.

var a = [1,2,3], b = ["gf","gdf","gdf"]

var options = a.map(function(value, index) {
 return { label: value, value: b[index] }
})

console.log(options)

If you prefer using ES6 and arrow functions, you can achieve the same result like this.

var a = [1,2,3], b = ["gf","gdf","gdf"]

var options = a.map((v, i) => ({label: v, value: b[i]}))
console.log(options)

Answer №2

If you want to create a custom function called mapn that can iterate over multiple arrays at once and call a function using elements from each array as arguments, you can do so like this:

array1 = [1, 2, 3]
array2 = ["gf", "gdf", "gdf"]

function mapn(arrays, fn) {
  return arrays[0].map((_, i) => fn(...arrays.map(array => array[i])));
}

console.log(mapn([array1, array2], (label, value) => ({label, value})));

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

Not every item in the array has been allocated to the model

I am encountering an issue with loading all the elements of an array from my ExpressJS backend to my frontend framework OpenUI5. Despite having an array of 520 elements, only the first 100 elements are being loaded into the model. How can I ensure that all ...

Customizing Your JQuery.awesomeCloud.plugin with a Tooltip Functionality using jQuery

Is it possible to integrate a jQuery Tooltip feature when hovering over specific words in a word cloud? I am currently using [jQuery.awesomeCloud.plugin]:https://github.com/indyarmy/jQuery.awesomeCloud.plugin If there is an alternative method to add toolt ...

Express.js code is experiencing difficulties with autocomplete functionalities

jQuery autocomplete code example [Express JS code for retrieving data][2\ Example of fetching data in Express JS ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

Navigating to the parent Vue component in a Vue3 project with Composition API structure in WebStorm

After transitioning to Vue3 and embracing the Composition API style, I find myself missing a small convenience that I had when developing in the previous Options API pattern. In WebStorm/IntelliJ IDE, I used to be able to command-click (Mac) on the "export ...

Check 2 arrays for common values and eliminate them

I am working with two arrays The first array looks like this: $sql1 = "SELECT userid FROM interests where interest='".$interest."' and userid!='".$myuserid."'"; $result1 = mysqli_query($conn, $sql1); if (mysqli_num_rows($resul ...

Pluck() method in Laravel retrieves a single row instead of a collection

I am currently working on developing a dropdown menu, and in order to achieve this, I require a JSON format with key-value pairs. I attempted to use the pluck() helper function, but it seems to be returning only a single row instead of the expected results ...

Trouble arises with Pagination feature of Mui Data Table

Currently, I am working on a project that involves retrieving data from the CoinMarketCap API and presenting it in an MUI Data Table (specifically a StickyHeader Data Table). However, I have been encountering difficulties with changing the color of the tex ...

Form a collection using multiple elements

I'm attempting to combine multiple arrays into a single array. For instance : array1= ['Joe','James','Carl','Angel','Jimmy',]; array2= ['22','11','29','43',&apo ...

What is the best way to conceal a Boostrap Navbar using jQuery?

Attempting to create a hidden side navbar using Jquery and Bootstrap 4. Struggling with the .on('click', ...) event handler for a button not hiding the sidebar as expected despite all files loading correctly according to the developer tools. Atte ...

Ensure that the value is updated upon clicking on the radio buttons and store the value in a session variable for

I'm working on a feature that involves two radio buttons: one for shipped and the other for not shipped. The requirement is that when the first radio button is clicked, an amount of 100 should be added to the total price. If the second radio button is ...

Would you like to learn how to set an auto-play video as the background in a webpage section, similar to the one found on http://www8.hp.com/in/en/home.html?

I was browsing the HP-India website and noticed they have a cool autoplay video in the background of a section below the header. I would love to recreate something similar on my own website. Any tips on how to achieve this? ...

Guide to obtaining scope within a nested directive

My problem lies in a nested directive within my code. I am attempting to pass a function from the nested directive to my controller, but for some reason, the function is not being triggered. Here is an excerpt of my main directive HTML: <div class="pa ...

Issue with body element displacement when utilizing Bootstrap 5.2 toast component

While utilizing a Bootstrap 5 toast, I noticed that it causes the entire body to shift down. I suspect that there may be an issue with how I am handling relative and absolute positioning attributes, but I am uncertain. This is my first time using Stack Ove ...

Synced Slideshows

Currently experimenting with the Owl Carousel plugin to create multiple synced carousels using their demo at the link below. However, I'm facing a specific issue when dealing with different numbers of small items in each carousel. I've successfu ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Combining Data from Header to Body using HTML5 and JavaScript

I am struggling to figure out how to transfer variables declared in the script from the header of my code to the body. Specifically, I want to capture the user input in the script and replace a placeholder in the body. Here is an example of what I am tryin ...

An undefined error for the variable 'y' in a JavaScript AJAX scenario

I'm completely new to JavaScript and struggling with writing a code that dynamically counts the words on a webpage. Currently, this piece of code is enclosed within a 'whenkeydown' function: var text = $(this).val(); var word=text.split(" ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

When navigating to a new route using history.push in React, it's important to ensure that the correct state is

My goal is to implement a smooth exiting animation with framer motion based on the user's current route and next destination. I specifically want the background to slide away only when transitioning from route A to route D. To achieve this, I decided ...