What is the proper way to arrange this particular array?

I'm having trouble with sorting this array. The array contains objects with SortTime and Operation values like this:

array = [ {SortTime : 123456, Operation : Assigning}, {SortTime : 4567 , Operation: Assigning}, {SortTime : 123456 , Operation: Assigned} ]; 

When comparing array[0] and array[2], I want to maintain the order so that "Assigning" comes before "Assigned".

Each of these numbers is an epoch number, so I need the algorithm to preserve the original order if two numbers are equal (e.g., if array[4] = 12345 and array[5] = 12345, I don't want them to switch positions in the final order).

    array.sort(function(a, b) {
        if (a.val.SortTime === b.val.SortTime) {
            return -1;
        } else {
            return a.val.SortTime - b.val.SortTime;
        }
    });

This approach isn't working because it often swaps positions of equal numbers. I apologize if my explanation is unclear. Thank you for your help!

Answer №1

To maintain the relationship between items with the same time, consider adding an index property to the objects and then sorting based on both time and index.

This approach results in a stable outcome due to the inclusion of the index.

var data = [
        { TimeStamp: 123456, Action: 'Update', index: 0 },
        { TimeStamp: 912345, Action: 'Delete', index: 1 },
        { TimeStamp: 123456, Action: 'Create', index: 2 }
    ]; 

data.sort(function (x, y) {
    return x.TimeStamp - y.TimeStamp || x.index - y.index;
});

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

Answer №2

If you're looking for a reliable way to sort, consider using a stable sort algorithm. You can find a variety of options on Wikipedia's list of stable sort algorithms.

For a practical example, here is an implementation of the merge sort algorithm from Rosetta Code available at this link:

function merge(left, right, arr) {
  var a = 0;
 
  while (left.length && right.length) {
    arr[a++] = (right[0] < left[0]) ? right.shift() : left.shift();
  }
  while (left.length) {
    arr[a++] = left.shift();
  }
  while (right.length) {
    arr[a++] = right.shift();
  }
}
 
function mergeSort(arr) {
  var len = arr.length;
 
  if (len === 1) { return; }
 
  var mid = Math.floor(len / 2),
      left = arr.slice(0, mid),
      right = arr.slice(mid);
 
  mergeSort(left);
  mergeSort(right);
  merge(left, right, arr);
}
 
var arr = [1, 5, 2, 7, 3, 9, 4, 6, 8];
console.log(arr);
mergeSort(arr)
console.log(arr);

Answer №3

To see a live demo, visit JSFiddle

let data = [ 
     { 
       Length: 54321, 
       Task: 'third task'
     }, {
       Length: 8765,
       Task: 'Calculating'
     }, {
       Length: 54321,
       Task: 'fourth task'
     }];

let duplicate = [...data];

duplicate.sort(function(x, y) {
    if (x.val.Length === y.val.Length) {
        return data.indexOf(x) - data.indexOf(y);
    } else {
        return x.val.Length - y.val.Length;
    }
});

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

How can I export an array in Ajax/PHP to the user as a .txt file?

Currently, I am working on a PHP file named "php-1" that is responsible for generating an HTML page. This particular file requests input from the user and once the user clicks on a button labelled "getIDs" (it's worth noting that there are multiple b ...

Get the PDF document via FTP by utilizing an XMLHttpRequest and a generic handler

Attempting to download a PDF file from an FTP server using a JQuery Ajax request. The reference used was found at . Below is the Jquery ajax call being made: $.ajax({ xhr: function () { var xhr = new window.XMLHtt ...

Refreshing a web page in Internet Explorer can cause the HTTP Header content to be altered

As I monitor my dashboard retrieving continuous data from an SAP server, I stumbled upon a solution to fetch the current server date. This approach allows me to display when the dashboard was last updated, and this date is displayed in the DOM. //Method f ...

"Seamless responsiveness in design with jQuery, but encountering compatibility issues

My usage of jQuery is quite basic to ensure that elements are properly positioned when they are moved: function ipad() { var width = jQuery(window).width(); if (width < 1200 && width >= 768){ //if tablet jQuery('.mobbut').css(&apo ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...

Could you explain the distinction between Node.bind() and Template Binding?

Currently, I am exploring the documentation for Google Polymer and have come across two types of data binding - Node.bind() and Template Binding. Can someone please explain the distinction between Node.bind() and Template Binding to me? ...

Is there a way to retrieve information from a different object?

Access the code on Plunker I am working with two data structures - ingredients and recipes [{ "id":"1", "name": "Cucumber" }, .. ] and [{ "id":"1", "name": "Salad1", "recipein":[1, 3, 5] }, { ... } ] My goal is to ...

Tips for stopping Infinite Scroll from loading pages when the tab is inactive

I'm currently developing a website using Bootstrap 4 and jQuery, which consists of 3 tabs, each containing masonry elements loaded on scroll with the Infinite Scroll plugin. I'm trying to figure out a way for the Infinite Scroll to only load cont ...

Showcasing a JSON attribute in the title using AngularJS

I'm struggling to display the Title of a table. Here is where I click to open a "modal" with the details: <td><a href="#" ng-click="show_project(z.project_id)">{{z.project}}</a></td> This is the modal that opens up with det ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

Exploring the best practices for organizing logic within Node.js Express routes

I'm currently utilizing the https://github.com/diegohaz/rest/ boilerplate, but I am unsure about the best practice for implementing logic such as QR code generation and additional validation. My initial thought was to include validation and password ...

The listener is not activating the AJAX function

It seems like the function validate() is not being called in the listener, causing an error and preventing data from being added to the database. Here is the code snippet from index.php: <!DOCTYPE html> <html> <head> <title>< ...

Creating nested namespaces with interfaces in Typescript type definitions

In my Javascript project, I am trying to define typing for a specific structure. Consider the following simplified example: a | + A.js + b | + B.js Here we have a folder 'a', and inside it there is another folder 'b'. My goal is t ...

Using Javascript to map an array with objects from a different array and then returning the computed array

I'm struggling to solve a seemingly simple issue. I have an array that looks like this: Array 1: [ { "id": 1, "date": "2019-03-27", "time": 1, "max_tasks": 3, "reservations": [ 5, 2 ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

A guide on how to successfully send multiple arguments to a single Javascript method by utilizing thymeleaf onclick (th:onclick) functionality

I attempted to use the code below, but unfortunately it did not work as expected. Can you please provide me with a solution? Javascript Code ---> function passValue(id, name){ console.log(id) console.log(name) document.getE ...

Is there a way to make jQuery Fancybox recognize my object as a valid parameter for opening?

I'm dealing with some HTML code that looks like this: <div id="logos" class="downloadlist"> <ul> <li><a href="/toolkit/logos/download.jpg" data-image="images/toolkit/logos/one.jpg">First Logo</a></li> ...

Performing addition operations on numbers entered through an HTML input field using PHP

I am looking to create a feature where the numbers entered in an input form are added together. I need to store these numbers in an array and have them display in a new line when a button is clicked. Here is the HTML code for the input field and button: ...

Utilizing ng-repeat to fetch and display an array of objects stored in Firebase

I am currently facing an issue while trying to access a list of notes from Firebase using AngularJS. I am unable to display the retrieved data even though there are no error messages appearing in the console. Notes.controller('ListGroupCtrl', ...

Obtain the value of the input

I need assistance with the input below: <input value="25" data-hidden-value="25" name="associations[agencies][ids][]" data-hidden-name="associations[agencies][ids][]" class="string" type="hidden"> This particular input is generated dyna ...