Combining two arrays without using concatenation, each from separate arrays but sharing one common variable

I'm struggling to combine two arrays in a specific manner and can't quite figure out the correct syntax to achieve this.

primaryData = [1,2]
secondaryData = [3,4]
label = [label1, label2]

Currently, I have this working

         data = $.map(labels, function(v, i) {

            return [[" " + v, " " + primaryData[i], " " + secondaryData[i]]] ;

        });

This produces the output:

[["label1", "1"], ["label2", "2"]]

Resulting in two arrays within an array.

However, my desired outcome is:

[["label1", "1"], ["label2", "2"], ["label1", "3"], ["label2", "4"]]

In essence, repeating the same process twice with "labels" and then incorporating numbers from different sources.

I've attempted the following:

         data = $.map(labels, function(v, i) {

            return [[" " + v, " " + primaryData[i]], [" " + v, " " + secondaryData[i]]];

        });

However, this yields:

[["label1", "1"], ["label1", "3"], ["label2", "2"], ["label2", "4"]]

It appears that the arrays are merging in a concatenative manner. Using + instead of comma separation results in 2 objects within an array rather than 2 arrays within an array.

Answer №1

To create a new array, you can combine the values from primaryData and secondaryData. Then, using the remainder operator, map the value of label with the iterating array.

var primaryData = [1, 2],
    secondaryData = [3, 4],
    label = ['label1', 'label2'],
    result = primaryData.concat(secondaryData).map(function(a, i) {
        return [label[i % 2], a.toString()];
    });
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

One approach is to utilize a basic for loop"

var items = [];

for(var j = 0; j < 6; j++) {
  items.push(["name" + (j % 3 + 1), (j + 1).toString()]);
} 

console.log(items);

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

Having difficulty extracting only names from the database with mongoose

My goal is to retrieve the value of all the name keys stored in my database. Each document in the database has only one key, which is the "name" key. Below is the code snippet that I need assistance with: user.find({}, 'name', function(err, user ...

Trapped in the dilemma of encountering the error message "Anticipated an assignment or function: no-unused expressions"

Currently facing a perplexing issue and seeking assistance from the community to resolve it. The problem arises from the code snippet within my model: this.text = json.text ? json.text : '' This triggers a warning in my inspector stating: Ex ...

Is it possible for the original object to be altered when passing it as a parameter to a function in a different file?

When you update an object passed as a parameter, will the updates be reflected "upwards" if the method receiving the parameter is in a different file? Or will the object retain its own context despite being passed down? ...

Guide: "Changing an HTML element's class by utilizing its id attribute"

This is the HTML code snippet I am working with: <li class="treeview" id="account_management"> I need to select the element with the id of "account_management" and update its class from "treeview" to "treeview active" in order to ...

Tips for effectively sharing content on social media from your Vuejs application

I have been using the vue-social-sharing library to enable social media sharing on my website, and overall it's been working well. However, I am facing a problem where when I click the Facebook share button, it doesn't share the title, descriptio ...

"Experience the latest version of DreamFactory - 2.0.4

I'm encountering a 404 error when I send a request to my new DSP. GET http://example.com/api/v2/sericename/_table/tablename 404 (Not Found) Upon checking the Apache error.log, I found this message: ... Got error: PHP message: REST Exception #404 &g ...

Implement a Bootstrap button that can efficiently collapse all elements in one click

Within my HTML file, I have included the following code: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <div class="list-group list-group-flush"> <a href="javascript: void(0)" da ...

Display the value in Vue.js as a price format while maintaining it as an integer

I have created a Vue component called "formatted-number" which takes in an integer value (e.g. 1234) and currently displays it as a string (e.g. "12.34") to represent a price in a textfield, with the appropriate "," or "." based on the country. However, I ...

Learn how to retrieve a jqGrid ajax Nested Array of Json string in C# using Newtonsoft Json

I am attempting to parse a JSON string and extract the array values within it. {"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\ ...

Why is my jQuery SlideReveal not displaying on page load?

Can anyone provide some help? I am currently using the jquery.slidereveal.js plugin from ''. The plugin works well when manually clicking the trigger to open and close the menu. However, I would like it to default to its last state on page load, ...

What techniques do platforms like Twitch, YouTube, Twitter, and Reddit use to dynamically load pages and update the URL without triggering a full reload?

Have you ever noticed that on some websites, when you click a link the page goes blank for a second and shows a loading indicator in your browser tab? However, on platforms like YouTube and Twitch, clicking a link smoothly transitions to the new page wit ...

AngularJS: Issue with ng-show and ng-click not functioning when button is clicked

I have a specific requirement where I need to display and hide the description of each column in a table when a button is clicked. Here is the visual representation of what I have: the table In my HTML code, I have defined a button with ng-click as a func ...

Is it possible for a dash in a GET variable name to cause issues with req.query in NodeJS Express?

I am currently developing a GET endpoint in Node.js using Express to handle the following variable: ?message-timestamp=2012-08-19+20%3A38%3A23 However, I am facing difficulty accessing it through req.query. Whenever I try to access req.query.message-time ...

swap out an element in an array with an extra element

My array contains elements with both id and des properties. I would like to add an additional property like value:0 to each object in the array. I achieved this using a loop. let data = [ { "id": 1001, "des": "aaa" }, { ...

What is the best way to retrieve web pages from the cache and automatically fill in form data when navigating to them from different pages on my website?

On my website, I have multiple pages featuring forms along with breadcrumbs navigation and main navigation. Interestingly enough, the main navigation and breadcrumbs share some similarities. However, my desire is that when users click on breadcrumb links, ...

How can I parse URL paths in jQuery for ASP.NET?

I want to incorporate "~/" and have it resolved on the client side. Here is an example of what I am trying to do: <a href="~/page.aspx">website link</a> <img src="~/page.aspx" /> In my ASP.NET code, I have my base URLs set up like this ...

Implement the geocomplete feature following an ajax event

When I click a button, it adds an input box for entering an address. To assist with auto-completion of the address, I'm using the geocomplete plugin. However, I've noticed that the geocomplete functionality only works on input boxes generated wit ...

Using a nested loop in Javascript to fetch JSON data

My goal is to display Categories and their corresponding subcategories in a specific order. However, my current method of using loops within loops is not producing the desired outcome: Category(Mobile) Category(Laptop) Subcategory(Iphone4) Subcategory(Iph ...

Comparing the distinction between assigning values to res and res.locals in a Node.js application using Express

Greetings! I am inquiring about the utilization of res (Express response object) and res.locals in Express. During my exploration of nodejs, I came across a code snippet that consists of a middleware (messages.js), a server (app.js), and a template (messa ...

Replace minor components (SVG) within the primary SVG illustration

I'm interested in transforming SVG elements into the main SVG element. For example, let's say the black square represents the main SVG element. I want to change elements 1, 2, and 3 to different SVG elements using JavaScript code. However, I am u ...