Divide arrays and merge them into new arrays depending on their position using indexOf in JavaScript

I am looking for a way to iterate through multiple arrays, for example:

array1 = [ "1", "2", "3" ];
array2 = [ "a", "b", "c" ];
array3 = [ "apples", "bananas", "cheese" ];

I want to combine them into new arrays based on their index positions like this:

result1 = [ "1", "a", "apples" ];
result2 = [ "2", "b", "bananas" ];
result3 = [ "3", "c", "cheese" ];

Any suggestions would be greatly appreciated. Thank you!

Answer №1

Combine the arrays into a temporary array, then reassign them to their original variables (see fiddle):

var numbers = [ 1, 2, 3 ];
var letters = [ "a", "b", "c" ];
var words = [ "apple", "banana", "cherry" ];

var tempArray = numbers.map(function(num, index) {
    return [num, letters[index], words[index]];
});

numbers = tempArray[0];
letters = tempArray[1];
words = tempArray[2];

Answer №2

To accommodate arrays of varying lengths, you can simply add another array like array4, or use arrays with different lengths:

var array1 = ["1", "2", "3"],
    array2 = ["a", "b", "c"],
    array3 = ["apples", "bananas", "cheese"],
    result = [array1, array2, array3].reduce(function (r, a) {
        a.forEach(function (b, j) {
            !(j in r) && r.push([]);
            r[j].push(b);
        });
        return r;
    }, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

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

What is the best way to incorporate the information from my CSV file onto my website?

I am currently working on a project where I need to extract data from a CSV file and display it on my website. The idea is to use two values as x and y coordinates, similar to a graph, and retrieve the data at that specific location. Here is the HTML code ...

Exploring the JSON object and dynamically incorporating elements into it is my goal as I navigate through AngularJS

I'm seeking a way to display the entire JSON data in a tabular format, with the ability to dynamically loop through any additional values that are added. Here is an example of my current JSON: $scope.tableContent = [ { id: 1, ...

What is the best way to give individual names to items in a string array without altering their values?

As a newcomer to android development, I am working on a project that involves a spinner, string array, and a JSON adapter. My goal is to have the string array display different item names but with the same value. Note: The JSON data is sourced online. ...

Steps for displaying a loading gif animation prior to retrieving text content using JavaScript

Before fetching the PHP result, I want a loading GIF image to display within the div section. <!DOCTYPE html> <html> <head> <title> CTR Calculator Tool | Free Click Through Rate Online Calculator </title> & ...

Execute a function in the background, even if the browser has been shut down

Is it possible to run a JavaScript function in the background, even after the user has closed the browser? I know this can be achieved in android apps, but I'm not sure about JavaScript. ...

Explore the AngularJS ui-routing project by visiting the website: https://angular-ui.github.io/ui-router/#resources

I am currently working on creating a sample app using AngularJS ui-routing. There is a tutorial that I am following which can be found here When I try to run the site locally in Chrome, I am encountering some errors in the console. Below are the errors tha ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

What methods can be used to add a delay to a toggleClass event in order to prevent rapid

After implementing the jQueryUI toggleClass delay function, I noticed that it introduces a delay before the event occurs instead of setting a specific timing for when it can be triggered again. I have multiple DIVs that switch classes when hovered over us ...

What is causing an error when using Array.push(), while Array.concat() works without any issues?

I'm attempting to merge an array with an existing array. The original data is structured like this: props: { ItemData: // This prop receives data from the parent component, which originates from a Vuex store. { type: Array, default: null ...

Leveraging Angular CLI in conjunction with the newest AspNetCore Angular 4 Single Page Application template

I'm currently experimenting with using Angular CLI alongside the latest JavaScriptServices AspNetCore Angular Spa template. In the past, I would simply copy and paste a .angular-cli.json file into my project's root directory, change "root" to "C ...

On initial load, React router switch fails to find a match

I am encountering an issue with my switch and react-router. Whenever I open a new tab and navigate to any path, it always redirects me to /login. However, if I remove the bottom switch (the one without a path - the default), everything works as expected. A ...

i18next initialization problem detected

I've implemented the i18next script in my jQuery Mobile page within a Cordova/PhoneGap app. At the bottom of my HTML page, I have included the following scripts: <script src="js/jquery-1.8.3.min.js"></script> <script sr ...

When the register button is clicked on the registration page, duplicate emails are being stored in MongoDB

Whenever I try to register with the same email on the registration page, it still gets recorded in my MongoDB database when I don't expect it to be saved. I attempted to set 'unique: true' for the email variable in User.js like this: import ...

How do I add an onClick event to a <span> element within a react-contenteditable component in React?

Is it possible to implement a similar functionality like this: <span onClick={(e) => console.log(e)}>Testing</span> Within the context of react-contenteditable in order to handle the click on the keyword Testing? Using the html prop, only ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Experience interactive video playback by seamlessly transitioning a webpage video into a pop-up when clicking on an

I want to have a video play as a pop-up when the user clicks a play button, while also fading out the background of the page. It should be similar to the way it works on this website when you click to watch a video. How can I achieve this? <div class=" ...

What is the most efficient way to calculate the total of all numbers within a range using this particular JavaScript function?

Currently tackling a coding challenge on Free Code Camp The task involves receiving an array of two numbers and calculating the sum of those two numbers along with all numbers in between. The order of the numbers in the array is not fixed. While the sugg ...

Issue with AngularJs: Clicking the same button multiple times does not produce the expected result

I developed a web page using Angular Js. When I move to a different page from the Home page and then return to the Home page by clicking the button, it functions as expected. However, upon clicking the Home button again, I anticipate a page refresh (sinc ...

The pie chart is unable to render due to issues with accessing the external JSON file in Ext

I attempted to create a pie-chart using extjs, but unfortunately, the pie-chart is not showing up. Interestingly, when I pass the JSON data through AJAX inline, it works perfectly fine. However, when I try passing it through a file, it doesn't work a ...

Django views functions do not receive any data during execution

Things are running smoothly, but it appears that the post function in views.py is not receiving any data. Also, how can I create a submit button using pure JavaScript without reloading the page? views.py: from django.shortcuts import render from rest_frame ...