Create arrays to display their respective index numbers

Here is an array that I am working with:

var myArray = [12, 24, 36, 48, 60, 15, 30];

I am trying to create a new array of arrays that includes the index numbers from the original array in the new array. The final result should be formatted like this:

var myNewArray = [
    [1, 12],
    [2, 24],
    [3, 36],
    [4, 48],
    [5, 60], 
    [6, 15],
    [7, 30]
];

Answer №1

Utilizing Array.prototype.map(), you can create a new array by taking into account the value and index of the original array.

See Demo

var myArray = [12, 24, 36, 48, 60, 15, 30],
    newArray = myArray.map(function (value, index) {
        return [index + 1, value];
    });

Just a heads-up: JavaScript arrays start at index 0, meaning the first element is at index 0.

Answer №2

let numbers = [12, 24, 36, 48, 60, 15, 30], 
indexedNumbers = numbers.map(function(item, index){
    return [index+1, item];
});
indexedNumbers.join(']\n[');


/* The resulting array is: */ [
    [1, 12],
    [2, 24],
    [3, 36],
    [4, 48],
    [5, 60],
    [6, 15],
    [7, 30]
]

Answer №3

It really is that straightforward:

let myNumbers = [12, 24, 36, 48, 60, 15, 30];
let myNewNumbers = [];
for (let i = 0; i < myNumbers.length; i++) {
    myNewNumbers.push([i+1, myNumbers[i]]);//you can also just use i depending on the index you want
}

You can make it even faster by storing the length of the array:

for (let i = 0, let len = myNumbers.length; i < len; i++) {}

Based on my findings and research - Javascript's built-in for loop outperforms array map when it comes to iterating through arrays. You can check out this interesting benchmark here.

I hope this information is helpful!

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

multiple executions of mouseup() within a mousedown() event

$("#canvas").on("mousedown", function(e){ var X1 = (e.pageX - this.offsetLeft) - 8; var Y1 = (e.pageY - this.offsetTop) - 8; $("#canvas").on("mouseup",function(e){ var X2 = (e.pageX - this.offsetLeft) - 8; var Y2 = (e.p ...

How can I extract the width of an uploaded image and verify it using JavaScript?

Is it possible to retrieve the image width through upload using PHP and then validate it in JavaScript? $_FILES['image'] If the image size is not equal to 560px, can we return false and display an alert message using JavaScript? Also, I am won ...

Python program to iterate through a matrix and verify the presence of each value in a vector

For my analysis, I have created a vector called possibleGrades containing the values [-3, 0, 2, 4, 7, 10, 12]. Now, I need to identify which cells in a given matrix do not correspond to any of these grades from the vector: [[ 7. 7. 4. ] [12. 10. 10 ...

How can I duplicate an element twice in AngularJS, without having them appear right after each other?

Within my AngularJS template html file, I am faced with a dilemma regarding an html element: <div>This is a complex element that I want to avoid typing multiple times</div> My challenge is that I need this element to show up twice on my websi ...

Tips for improving the efficiency of the find_average_number(array) simple function?

I successfully completed a CodeWars challenge where I wrote the function find_average to calculate the average of numbers in an array. However, I now have some questions: 1) How can I optimize this code in terms of Big-O notation? Is there a way to reduce ...

No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time. The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser ...

Troubleshooting Rails 4: Handling a 404 Not Found Error When Making an AJAX Call to a

After spending about an hour trying to figure this out, I am still stuck... The action in my oferts_controller.rb file looks like this: def update_categories @categories = Category.children_of(Category.find(params[:categories])) respond_to ...

D3 with Y-axis flipped

After creating a bar plot, I noticed that my Y axis is reversed and the scale seems off. I've been struggling to figure it out on my own. Here's a link to the Jsfiddle with the code. If you want to give it a shot somewhere else, here is the code ...

Maya model being loaded using Three.js

I've been following a tutorial on how to load Maya models using Three.js, which you can find here. Everything is going smoothly, but the tutorial only covers loading models with a single texture. Below is the source code snippet from the tutorial: ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

Unable to remove spaces in string using Jquery, except when they exist between words

My goal is to eliminate all white spaces from a string while keeping the spaces between words intact. I attempted the following method, but it did not yield the desired result. Input String = IF ( @F_28º@FC_89º = " @Very strongº " , 100 , IF ( @F_28 ...

Using TypeScript to consolidate numerous interfaces into a single interface

I am seeking to streamline multiple interfaces into one cohesive interface called Member: interface Person { name?: { firstName?: string; lastName?: string; }; age: number; birthdate?: Date; } interface User { username: string; emai ...

When using JSON stringify, double quotes are automatically added around any float type data

When passing a float data from my controller to a JavaScript function using JSON, I encountered an issue with quotes appearing around the figure in the output. Here is the JS function: function fetchbal(){ $.ajax({ url: "/count/ew", dataType: "jso ...

Placing a hyperlink within template strings

Currently, I am working on implementing a stylish email template for when a user registers with their email. To achieve this, I am utilizing Express and Node Mailer. Initially, my code appeared as follows: "Hello, " + user.username + ",&bs ...

Reactively created menu using JQuery

Looking to implement a dynamic JQuery menu using React (ES6). Utilizing the JQuery menu examples (https://jqueryui.com/menu/) as a guide, however, those examples only cover static menus. It doesn't clarify how to modify menu items like updating labels ...

"Encountering an issue with toUpperCase function in Next.js when incorporating slug - any

Clicking on the following link will take you to the Next.js API reference for configuring headers: https://nextjs.org/docs/api-reference/next.config.js/headers When adding the x-slug key, the code snippet looks like this: module.exports = { async heade ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Troubleshooting Angular MIME problems with Microsoft Edge

I'm encountering a problem with Angular where after running ng serve and deploying on localhost, the page loads without any issues. However, when I use ng build and deploy remotely, I encounter a MIME error. Failed to load module script: Expected a ...

Make sure to verify the absence of a table entry. Is there a way to validate the 'Items' array if it comes back as null? JavaScript and DynamoDB implementation

I've been trying to determine the existence of an item in my DynamoDB database, but I'm having trouble finding a straightforward solution. I've resorted to using the getItem() operation. According to the documentation, this operation should ...

Implementing SweetAlert2 in Vue.js to create a modal prompt for confirmation prior to deleting an item

I'm encountering an issue with sweetalert2 while using Laravel Vue for my app development. My goal is to have a confirmation modal pop-up when deleting a row from the database. However, whenever I click "Yes", the item is successfully removed. But if ...