Exchanging the positions of two elements within a 2D array

I am having trouble sorting the 2-dimensional array based on column values. Here is the array:

var cl12 =  [[9, 10.5], [10, 11.5], [12, 13.5], [12.5, 14.5], [14.5, 15], [16, 18], [16, 17]]

In the above array, you can see that the last two elements have the same value for the 0th index, but they are not sorted correctly based on column values. For example, [16,18] should come after [16,17]. I tried using a for loop to sort the array completely like this:

 for(i=0;i<cl12.length;i++){
      if((cl12[i][0]==cl12[i+1][0]) && (cl12[i][1]>cl12[i+1][1])){
         var temp = cl12[i+1];
         cl12[i+1]=cl12[i];
         cl12[i] = temp ;
         }
       }  
     console.log(cl12)

However, when I run this code, I get an error in the console: Uncaught TypeError: Cannot read property '0' of undefined"

Answer №1

Make sure to compare each element with the one following it, so remember to only loop up until one less than the array's length.

for(i=0;i<cl12.length-1;i++){

var cl12 =  [[9, 10.5], [10, 11.5], [12, 13.5], [12.5, 14.5], [14.5, 15], [16, 18], [16, 17]]
for(i=0;i<cl12.length-1;i++){
  if((cl12[i][0]==cl12[i+1][0]) && (cl12[i][1]>cl12[i+1][1])){
    var temp = cl12[i+1];
    cl12[i+1]=cl12[i];
    cl12[i] = temp ;
  }
}  
console.log(cl12)

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

PHP's counterpart to the Javascript XMLHttpRequest

Recently, I have come across a PHP function that is quite interesting: function saveSnapshot() { header("Content-Type: application/JSON: charset=UTF-8"); global $CFG; $resString = "{\"Success\": \"True\"}"; $snapshotNa ...

The ng-cloak directive doesn't seem to be functioning properly

After writing some code to remove '#' tags from text input, I encountered an issue upon loading the page. The initial display showed '{{textWithHashes | textWithoutDashes}}', which is not appealing at all. I attempted to use ng-cloak to ...

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Using JavaScript regular expressions to find text that is not contained within an HTML tag

I am in search of a Regex pattern that can be used in node.js to match all text that is not part of an HTML tag or element. The challenge is to match text like "5", "ELT.", "SPR", " ", "plo", "Unterricht", " ", "&nbsp", and "plo" from a given ...

What is the correct way to utilize the karma-ng-html2js-preprocessor?

I'm working on a directive called stat24hour: angular .module('app') .directive('stat24hour', stat24hour); function stat24hour(req) { var directive = { link: link, template: 'scripts/widgets/templ ...

VueJS form validation does not account for empty inputs in both fields

One of the challenges I'm facing is generating a form with Vue.js using the input fields below: { name: 'first_name', type: 'text', label: 'First Name', placeholder: 'First Name', ...

The mouse pointer adjusts according to the event

I am working on an ajax request and I have implemented a feature where the cursor changes appearance. document.body.style.cursor = "wait"; This immediately shows the cursor as a spinning circle when the request starts. At the end of the request, I ch ...

Strategies for handling click events on multiple panels in C#

I have been developing an online checkers program and successfully implemented drawing the board and checkers on each square. The challenge I am facing now is programming the click events. I have code that changes the background color to blue and checker c ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

What is the best way to update the text within a Span element as the user moves through the Jquery slider?

Can I utilize jQquery to dynamically alter the text content of my "video_box_label" span element based on the active slide in my "flexslider" slideshow? For instance, when the slideshow transitions to the second slide, I want the text to change from "Mee ...

jQuery datatable loses highlight after page refresh

I am currently working with a datatable that utilizes ajax to load data. var table = $('#example').DataTable({ "ajax": "xxxxxx.aspx", stateSave: true, "aLengthMenu": [ [10, 25, 50, 100], [10, 25, 50, 100] ], ...

Search the table for checked boxes and textboxes that are not empty

Could you suggest alternative ways to express the following scenario? I have a table with 3 rows. Each row contains a column with 3 checkboxes and another column with just a text box. I would like it so that when the values are retrieved from the database ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...

Customize the React Material UI Autocomplete with a unique dropdown menu and a convenient Add Button feature located at

Seeking assistance in creating an autocomplete feature in React using Material-ui, with a unique custom dropdown design including a button labeled Add New Element positioned at the bottom. https://i.sstatic.net/6rY99.png Various attempts have been made t ...

Utilizing AngularJS to display numerous charts on a single webpage

Currently, I am looking for a solution to display multiple charts on the same page. My goal is to showcase individual performance through each chart for different persons. After exploring Google Charts, I noticed that it requires unique "id" attributes w ...

Adding several entries into mysql with the assistance of php

I've been attempting to input multiple records into my database table, but every time I try, all I see are zeros(0) inserted into the fields. Here's what I attempted: I used a foreach loop for insertion, but unfortunately it doesn't seem to ...

Utilize identical animations across various elements

I have a canvas animation in JavaScript that is currently limited to one canvas element with the id "stars". I want to be able to use this animation multiple times without repeating the code. Is there a way to add a class for the canvas elements instead of ...

I do not send JSON Express post for receiving

I have a question regarding sending JSON data to my Express server using request. However, when Express receives the data, it doesn't seem to be in the correct JSON format. Below, I will share the code related to this issue. The JSON I am sending ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Enhancing Your Web Page: Updating Values Using Flask

Here is my code snippet: app = Flask(__name__) @app.route("/") def Tracking(): lower = np.array([35, 192, 65]) upper = np.array([179, 255, 255]) video = cv2.VideoCapture(1, 0) times = [] total = 0 is_round = Fals ...