Ordering elements of array [i] based on sorting criteria of [i][0] and [i][1]

Looking to organize an array consisting of sets or pairs based on the first number in each pair.

Here is the code snippet:

function randomMap(numOfHills){
    for(var i=0; i<numOfHills; i++){
        xRandomForHills = Math.floor((Math.random() * 2000));
        if(xRandomForHills >= 1700){
            xRandomForHills = xRandomForHills - 300;
        }
        if(xRandomForHills <= 300){
            xRandomForHills = xRandomForHills + 300;
        }
        yRandomForHills = Math.floor((Math.random() * 300));
        if(yRandomForHills <= 100){
            yRandomForHills = yRandomForHills + 300;
        }
        hillArray.push([xRandomForHills,yRandomForHills]);

console.log("my Hill = " + hillArray[i]);
    }
    sortArray(numOfHills);
};

function sortArray(numOfHills){
    hillArray.sort(function(a, b){return b-a});
    hillArray;
    for(var i=0; i<numOfHills; i++){
    console.log("Sorted = " + hillArray[i]);
    }
    drawMap();
};

Debug information:

my Hill = 917,136
my Hill = 885,274
my Hill = 876,347
my Hill = 1011,184
my Hill = 563,273

Sorted = 917,136
Sorted = 885,274
Sorted = 876,347
Sorted = 1011,184
Sorted = 563,273

Desired sorting of the first part of the array:

my Hill = 917,136
my Hill = 885,274
my Hill = 876,347
my Hill = 1011,184
my Hill = 563,273

Sorted = 563,273
Sorted = 876,347
Sorted = 885,274
Sorted = 917,136
Sorted = 1011,184

Answer №1

Your x and y in sorting an array

Follow this example

sampleArray.sort(function(x, y){return x[0]-y[0]; });

JSFIDDLE

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

Create a PDF document using the combined HTML content

I am facing an issue with generating a PDF from HTML content. My goal is to convert all the content within a specific div into a PDF. I have tested out a few converters, but they only seem to convert HTML files. I do not want to convert the entire HTML fi ...

Requires a minimum of two page refreshes to successfully load

Our website is currently hosted on Firebase. However, there seems to be an issue as we have to refresh the website at least twice in order for it to load when visiting www.website.com. Update: We are unsure of what could be causing this problem. W ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Functionality of retrieving arrays from PHP via jQuery ajax (JSON) runs smoothly, however encounters issues specifically on web server

No solutions have been able to solve the problem at hand despite finding similar questions. function loadProject(id) { $.ajax({ url: 'loadDrumsetData.php', type: 'GET', data: { i: id }, ...

Error encountered: Difficulty rendering Vue 3 components within Google Apps Script

Currently delving into Vue and Vue 3 while coding an application on Google Apps Script. Following tutorials from Vue Mastery and stumbled upon a remarkable example by @brucemcpherson of a Vue 2 app functioning on GAS, which proved to be too challenging in ...

Understanding how to set the Content-Type in a Post request using Ajax with Node.js

Attempting to send an ajax request without a header in Node.js triggers an error: { [Error: unsupported content-type] status: 415, statusCode: 415 } However, when sending a request with a header, Node.js does not seem to respond. Here is my ajax funct ...

What is the best practice for AngularJs service methods: accepting an object or multiple parameters?

When creating Angular JS service methods, what is the recommended approach: accepting multiple parameters or utilizing an object? var getMessages = function (appid, userId, limit) { var data = { "appid": appid, "userId": userId, ...

Having trouble retrieving data from an array within a JSON object

I've spent countless hours searching for a solution to this issue, but no matter what I attempt, I keep running into the same error message. The dreaded error I keep encountering is: Fatal error: Cannot use object of type stdClass as array My curren ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

Using JSON to represent associative arrays in PHP syntax

Here is a question that consists of two parts. Firstly, there is a code snippet that makes a call to graph.facebook.com with user-defined parameters, resulting in a JSON response. Below is the code snippet: $RAW_DATA = json_decode(file_get_contents($URL_ ...

What is the best way to implement rate limiting for Next.js server actions?

In my current project, I have implemented server actions in next.js following the guidelines provided on Server Actions Although everything is functioning properly, I am now looking to add rate limiting to the server action to prevent potential spam or at ...

Uncaught ReferenceError: The variable in Next.JS is not defined

Within the server-side code of page.tsx, I have a client-side component called SelectType.tsx. The functionality should be as follows: When the user changes the value of the select component It triggers a function inside page.tsx The function is supposed ...

AngularJS: Issue with directive function not being executed

I created a directive in my code, but for some reason the function I provided to define the directive is not being called. It was working perfectly fine before, and now it just suddenly stopped without any clear explanation. Below is the code snippet of m ...

The concept of undefined in JavaScript when an if condition is applied

In Node.js, there is a method used to handle API requests. An unusual behavior occurs when dealing with req.query.foo - even if it has a value defined, it becomes undefined when used in an if condition as shown below. Additionally, another req.query.foo ...

Having difficulty installing Axios on Node, despite attempting various solutions found on StackOverflow without success

I am encountering an issue where Node is unable to locate the axios package that I installed. In an attempt to resolve this, I performed the following actions in NPM, believing it was an npm-related problem: npm uninstall axios npm cache clean --force npm ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

What is the process for transferring a JavaScript variable to a Java servlet?

I am trying to send a JavaScript variable to a Java servlet in a web application I am developing. Below is the HTML code: <p id="test">Some text</p> Here is the JavaScript code I am using: var myVar = document.getElementById('test' ...

Adding new elements to a list with Jquery, seamlessly integrating them without the need to

I am facing a bit of a roadblock in figuring out how to achieve this, mainly due to my limited understanding of JavaScript. The code that I have been looking at is as follows: http://jsfiddle.net/spadez/VrGau/ What I am attempting to accomplish is allowi ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

Is there an issue with Three.js canvas.toDataURL() function in Chromium browsers?

After performing a recent system upgrade, I noticed some issues with Chromium. One of them was a delay in loading my Three.js r85 project, which was resolved after upgrading to Three.js r90. However, I encountered a new problem with toDataUrl() not workin ...