Transform a set of numerical values in a JavaScript array into indexed pairs

Let's say I have an array of numbers presented in this format:

[5, 29, 1, 5, 4919, 109, 17]

My goal is to transform this array into pairs of numbers based on their index within the array. The desired output would look like this:

[[0, 5], [1, 29], [2, 5], [3, 4919], [4, 109], [5, 17]]

Any suggestions or examples on how to achieve this using javascript?

Answer №1

[2, 55, 6, 23, 8519, 130, 29].map(function(y,z){return [z,y];})

Answer №2

The previous response proposes the use of map, which is a viable solution and one that I would likely implement in my own code. However, it's worth noting that map was only introduced in ECMAScript 5, so it may not be compatible with older browsers without a polyfill.

If you're looking for a more universally compatible approach, a straightforward method could look something like this:

var input = [5, 29, 1, 5, 4919, 109, 17];
var output = [];
for (var i = 0; i < input.length; i++)
    output.push([i, input[i]]);

Alternatively, you could consider this alternative method:

var input = [5, 29, 1, 5, 4919, 109, 17];
var output = Array(input.length);
for (var i in input)
    output[i] = [i, input[i]];

Answer №3

Looking to fill the gaps in older browsers? Check out this handy library: - approximately 5.501 kilobytes in size.

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

Is there a way to make my JavaScript code function within an ASP.NET CSHTML file?

I am working on a web project where I have an HTML input for uploading a picture to my FTP server. I want to use JavaScript to detect changes on my upload button. This is the code in my CSHTML file: @using (Html.BeginForm("UploadFile", "Upload", For ...

Implementing a JavaScript function to trigger the 'GET' method upon page load repeatedly

I am facing a strange issue where a javascript function is running multiple times upon page load (7 times in Chrome, 3 times in IE, 7 times in Firefox, 6 times in Opera, 4 times in Safari, and 4 times in Edge). What's going on??? Moreover, the xmlHtt ...

Enter the specified text in the input field

My challenge involves dynamically changing a string value that needs to be inserted into an input field. (async () => { let index = 1004327; let browser = await puppeteer.launch({ headless: true, }); let page = await browser.newPage(); ...

establishing the dimensions of table data cells

I'm facing a challenge with setting the width and height for table data that changes dynamically based on different values. The dimensions of the table itself are not definite, so I need to find a solution. Here's the code snippet I'm curren ...

Activate html5 form validation when clicking on an asp.Net LinkButton using OnClientClick

I am working with a webform application Within the Master Page, I have created a form as follows: <body class="tile-1-bg"> <form id="form1" runat="server"> On my page.aspx file, the form includes the following elements: <div class="contr ...

Experiencing a bug in my express application: TypeError - Unable to access properties of undefined (reading 'prototype')

I've encountered the TypeError: Cannot read properties of undefined (reading 'prototype') error in my javascript file. Despite researching online, it seems that many attribute this issue to importing {response} from express, but I am not doi ...

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" }, { ...

React is informing that the `toggleNode` prop is not recognized on this particular DOM element

I have encountered the following warnings in my app, which I believe are causing it to not load all its features properly. Warning: React is indicating that the toggleNode prop is not recognized on a DOM element. If you intend for it to be a custom attrib ...

Error message: "Unable to find reference process. simple-peer Javascript"

Currently, I am delving into WebRTC and utilizing simple-peer, an npm package, with React and Socket.io. However, whenever I attempt to make a call, I encounter this error: _stream_readable.js:529 Uncaught ReferenceError: process is not defined at emit ...

Switching the position of a Button in Semantic UI React: Moving it from the Left to the

I need assistance with adjusting the position of a Semantic UI React Button. By default, the button is displayed on the left side, but I would like it to be on the right side instead. Can someone please provide guidance on how I can move the Semantic butto ...

Maximizing performance through strategic database structuring with PouchDB/CouchDB

Recently, I've been researching efficient ways to store and retrieve data for my time management/project capturing application. I would greatly appreciate any insights on which storage strategy to utilize, or suggestions for alternative approaches, es ...

Automatically Resizing an iFrame Height Upon Submit Button Click

Currently, I am facing an issue with a form that generates an iFrame for the Payment section. While the height of the iFrame is set correctly, whenever there are errors in the form submission and error messages appear, they push the submit button below t ...

Loop through a PHP array containing a mix of different data types

I am having trouble with the formatting of my array output. Array: Array ( [0] => Photography & Video:Online Video [1] => Photography & Video:Digital Files [2] => Shooting Types:Ring Shots [3] => Shooting Types:Wedding Shots ) Output: (Using ...

Encountering Uncaught Runtime Error in NextJs

Encountered an issue with my Nextjs website development where I am seeing an Unhandled Runtime Error. Error: Server-rendered HTML does not match text content. **Warning:** Discrepancy found between server and client text content: Server says "160 mins ag ...

The scroll event listener activates based on the distance I have scrolled

const processChatRead = useCallback(() => { const chatWindow = refEntries.current; if ( chatWindow.scrollTop > chatWindow.scrollHeight - 800 && activeRoom && conversations?.content?.length > 0 && ...

Using jQuery to select and automatically trigger a click on an anchor tag based on its class name

Is there a way to retrieve the class name of an anchor tag and automatically click it? See below for the code: <div id="testing"> <a class="download_now link_btn" href="#">Download Now<i></i></a> </div> ...

Add the useState hook from React to an array

Hey there, I need some help with my code. I am trying to add an element to my array, but it's not working as expected. Can you take a look at what I have written below? const [datesState, setDisabledData] = useState([ format(new Date(2021, 4, 1) ...

Having trouble with the downloadUrl function when trying to generate a Google map locator in Opencart?

Currently, I am working on the development of a website using opencart at Within the dealers.php file, there is a function named query() which searches postcodes in the database to retrieve store location results and outputs them in XML format. For exampl ...

Troubleshooting: Inconsistencies with AngularJS' ngmaxlength and ng-required

Input Type <div class="form-group" ng-class="{ 'has-error': loginForm.password.$dirty && loginForm.password.$error.required }"> <label for="password">{{ 'PASSWORD' | translate }} <span class="required-field"& ...

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...