Organize a collection of objects (with X and Y attributes) to ensure they are arranged from left to right and top to bottom

In the array, each item is placed on the stage with an x/y position. The top left most position should be items[0], with X as the primary positioning factor.

Initially, I considered using the following code:

var items = [m1, m2, m3, m4, m5, m6];

items.sort(sortMe);    

function sortMe(a, b)
{
    return (b.position[0] - a.position[0]) && (b.position[1] - a.position[1]);
}

However, this approach did not deliver the desired results.

Answer №1

sort() will either return 0 or a negative/positive number.

In this sorting function, priority is given to X:

function sortByPosition(a, b){
  if (a.x == b.x) return a.y - b.y;
  return a.x - b.x;
}

If you want to prioritize based on Y (the "natural" order):

function sortByPosition(a, b){
  if (a.y == b.y) return a.x - b.x;
  return a.y - b.y;
}

To achieve the desired outcome, replace your && with ||:

return a.x - b.x || a.y - b.y

Answer №2

Sorting algorithm for two-dimensional positions in JavaScript
{
    if( a.position[0]<b.position[0] || (a.position[0]==b.position[0] && a.position[1]<b.position[1] ) ) return 1;
    if( a.position[0]==b.position[0] && a.position[1]==b.position[1]) return 0;
    return -1;
}

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

Updating the VueJS DOM when a different value is chosen from the dropdown menu

I am facing an issue with updating the DOM using the following logic: index.vue [Template Part] <div> <div v-for="obj in objects" :key="obj.id"> <select v-model="obj.quantity" @change="qtyChange(obj)"> < ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...

Using React to create multiple modals and dynamically passing props

Each item in my list (ProjectActivityList) has an Edit button which, when clicked, should open a modal for editing that specific item. The modal requires an ID to identify the item being edited. var ProjectActivities = React.createClass({ onEditItem: ...

Is there a more efficient method in ThreeJS to generate and display a lush woodland filled with unique trees?

I am facing the challenge of rendering a vast forest comprised of over 100,000 simplistic trees in ThreeJS. It is not feasible to create individual meshes for each tree. Currently, I am using GeometryUtils.merge to combine the trees into one large geometry ...

Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop. The target page for this button implementation can ...

The updateItem function in the JSGrid controller was not called

Currently, I am working on a project involving js-grid. However, I have encountered an issue where the updateitem function of the controller is not being invoked when attempting to update a column field. Additionally, the field resets to its old value wi ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

Is using the new Date function as a key prop in React a good

In my React code, I have been using new Date().getTime() as key props for some Input components. This may not be the best practice as keys should ideally be stable. However, I am curious to know why this approach is causing issues and why using Math.random ...

npm unable to locate the specified file

I'm currently following a tutorial on creating a Google Maps clone. After completing the build, I tried running the npm start command but encountered the following errors: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\m ...

Unable to successfully delete all channels in discord.js

I'm currently working on a bot designed to delete all channels within a Discord server. Here is the code I have written: const { Client, GatewayIntentBits } = require("discord.js"); const client = new Client({ intents: [ GatewayIntent ...

How to automatically generate a serial number using JavaScript each time a click event occurs

continuous problem with repeated serial numbers Serial number remains the same after each click $(document).on('click', '.menu-item', function() { var menu_id = $(this).attr('id'); var _token = $('input[name="_ ...

Struggling to find a solution for changing the color of a select box when an option is chosen

Here's an example of the HTML I'm working with: <select onclick="colorchanger()"> <option name="white" value="0">--Select--</option> <option name="red" value="1">Work</option> <option name="green" value="2" ...

An unforeseen vow in lieu of an assortment

I'm currently working on a project involving node and mongo. To achieve parallel requests, I am utilizing a netlify serverless function that will be built using data from mongo records. Here's what I have done so far: paralellNum = 2; const filt ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

In Node.js, use the `[]` operator to select elements from an array of strings without including

In my situation, I am working with an array of strings which can sometimes be an array containing only one string. The issue is that when this happens, using array[0] to retrieve the value does not return the entire string but rather just the first charact ...

Challenges arise when attempting to return an early resolution within promises in JavaScript

I have a function that determines further execution within itself and needs to use promises since it is asynchronous. An issue arises where the function continues execution even after resolving. Here's my code: function initializeApplication() { ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

.Nested ajax repeater with a slideToggle

I'm having an issue with a function that writes the value of a DIV to a cookie. The toggle code works fine, and I can iterate through the repeater elements to determine if a section should be hidden or not. However, when trying to use .show() or .hide ...