What is the best way to arrange this multi-dimensional array in order based on its id?

Need help sorting this Array by ID. This code snippet is not working as expected:

    var arr = new Array();

    arr.push({
    id: "9",
    datum: "XXX",
    start: "XXX",
    ziel: "XXX",
    hinfahrt: "XXX",
    ruckfahrt: "XXX",
    zuzahlung: "XXX"
    });

    arr.push({
    id: "3",
    datum: "XXX",
    start: "XXX",
    ziel: "XXX",
    hinfahrt: "XXX",
    ruckfahrt: "XXX",
    zuzahlung: "XXX"
    });

    arr.push({
    id: "6",
    datum: "XXX",
    start: "XXX",
    ziel: "XXX",
    hinfahrt: "XXX",
    ruckfahrt: "XXX",
    zuzahlung: "XXX"
    });



    arr.sort(function(a,b) {
    if (a[0] === b[1]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
    });

    console.log(arr);

I am struggling with using the sort function correctly. The desired output format should look like this:

{id: '3', datum: 'XXX', start: 'XXX', ziel: 'XXX', hinfahrt: 'on', …} 
{id: '6', datum: 'XXX', start: 'XXX', ziel: 'XXX', hinfahrt: 'on', …} 
{id: '9', datum: 'XXX', start: 'XXX', ziel: 'XXX', hinfahrt: 'on', …}

Answer №1

Here we have an array containing objects that need to be sorted based on a specific property within each object. To achieve this, you can utilize dot notation to access the desired property for comparison during sorting. Consider revising your sorting function as shown below:

arr.sort(function(a,b) {
    if (a.key === b.key) {
        return 0;
    } else {
        return (a.key < b.key) ? -1 : 1;
    }
});

Answer №2

Simply acquire the property directly by calculating its delta value.

const
    array = [{ id: "9", datum: "XXX", start: "XXX", ziel: "XXX", hinfahrt: "XXX", ruckfahrt: "XXX", zuzahlung: "XXX" },{ id: "3", datum: "XXX", start: "XXX", ziel: "XXX", hinfahrt: "XXX", ruckfahrt: "XXX", zuzahlung: "XXX" },{ id: "6", datum: "XXX",  start: "XXX", ziel: "XXX", hinfahrt: "XXX", ruckfahrt: "XXX", zuzahlung: "XXX" }];

array.sort((a, b) => a.id - b.id);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Leverage the power of an Express server to manage a Node.js application

I have a node.js application that communicates with a REST API hosted on a separate server. To control this application, I want to create a web interface using express.js which includes HTML, CSS, and Javascript. How can I enable the browser to interact w ...

Combine five string arrays into a single array

Is there a way to combine five arrays into one array? var arr1 = ['a','b']; var arr2 = ['c','d','n']; var arr3 = ['e','f']; var arr4 = ['g','h']; var arr5 = ['o ...

What is the best way to create a "Hello, world!" for Comet using AngularJS?

Struggling to figure out how to create a simple Comet proof-of-concept in AngularJS that involves the client making repeated Ajax calls rather than using streaming JavaScript. I've searched everywhere but haven't found a solution yet. Let's ...

Configuring webpack to serve static HTML files alongside a React application involves setting up the necessary webpack configuration to handle both types

I'm attempting to create a React app using Webpack that reserves specific paths for HTML static files without actually importing them into the React app. Here's an example: Expected Outcome: localhost:3000/any/other/path -> load React localho ...

What is the function of computeCentroids in Three.js?

While working on my custom geometry in three.js with TypeScript, I encountered an issue where the object appeared dark with Lambert material. To troubleshoot, I examined the source code and noticed that nearly every geometry class had the following two lin ...

Error: stdClass::$distance property is not defined in the Google Distance API response

I have been trying to resolve this issue for a few days without success. I am working with a coordinate dataset and trying to calculate the distance using those coordinates. However, when I run the code, I encounter the following errors: Message: Undefine ...

how to open a new tab using JavaScript with Selenium

My code is supposed to open a new window that goes from the login window to the main menu, module, reports, and finally the report name. The report name should be opened in the next tab. Issue: The report name is not opening in a new tab; it's openin ...

What is the process of importing a JSON data file and utilizing it within a React component?

As a beginner in React, I am struggling with the concepts of importing, exporting, and rendering components. I have a fakeData.json file within the same src/components folder as the component I want to render. Let's take a look at the structure: < ...

Use jQuery to switch back and forth between two different sets of classes

I am attempting to switch between two different sets of classes using jQuery. My goal is to change from one custom icon to a font-awesome icon upon clicking an element. While I have been successful in changing a single class, I am facing challenges when tr ...

Organizing Items in an Array/Vector to Form a Grid Pattern

I am looking to organize specific objects from a vector or array into a grid format. Currently, I have a method that does this when the objects are created. Here is the grid function I've developed: function ArrangeInGrid(uiRow:uint, uiCol:uint, iO ...

transferring form information in a modal without the need to redirect

I have a modal form that contains a file upload option and some additional data fields. Currently, upon clicking "Submit," the form redirects to the target page with all the data. I am looking for a solution where the data can be sent to the target page wi ...

Best practices for sharing data between controllers in an Angular application

It appears that this topic has been discussed before, but... While service or events can be used for this purpose, there is conflicting information online about the frequency of using events. Creating a separate service may not be the ideal solution eith ...

Currently waiting for the $resolved property of the AngularJs service

Here's a straightforward issue with what I hope is an equally simple solution. I've set up multiple services for handling CRUD operations with tags. myApp.factory('GetTags', ['$resource', function ($resource) { return $re ...

Remove the "hover effect" from an element using programming on mobile devices

There is an element on my webpage that has a specific set of styles for when it is hovered over. However, on mobile devices, this triggers the "sticky hover" effect, where touching the element applies the hover effect until the user touches another part of ...

Guide to displaying database results in an HTML dropdown menu by utilizing AJAX technology

Greetings! As a newcomer to the realms of PHP and AJAX, I am currently on a quest to showcase the outcomes of a query within an HTML dropdown using AJAX. Let's delve into my PHP code: $pro1 = mysqli_query("select email from groups"); I made an attemp ...

Execute the knockout function using jQuery

There's a scenario where I am trying to trigger a knockout method using jQuery. The Knockout viewModel has already been bound, but I'm unsure of how to call it using jQuery. Below is the snippet of my code: $(document).ready() { form_submit( ...

The external IP address cannot be accessed beyond the function scope in Node.js

Recently joining this community, I am in the process of retrieving my external IP through a package called "external-ip." The example code provided by them looks like this: const getIP = require('external-ip')(); getIP((err, ip) => { ...

The 'canvas' module could not be located in the system.Here are the required stacks:- /var/task/index.js- /var/runtime/index.mjs

I am currently developing a lambda function using the serverless framework. The function utilizes chartjs-node-canvas to create graphics, and everything runs smoothly on my MacBook when tested locally. However, when I deploy the function to AWS either dire ...

Pause the initial ajax data loading in Tabulator.js and instead load data only after the first filter is applied

Currently, I am utilizing the tabulator.js library and hoping to delay the loading of data until after the first filter is applied, rather than immediately upon page load. Is there a way to achieve this functionality using something like: initialAjaxLoa ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...