I am interested in organizing a three-dimensional array using JavaScript

Just the other day, I posted a question on PHP, but now I need similar help for JavaScript.

Here is my array :

var inboxMessages = {
    105775: { 
        0: {
            'id': 85,
            'thread_id': 105775,
            'message': "hello",
            'created_at': "May 20, 2015",
            'datetime': 1432118191,
            'sender_id': 13,
        },
        1: {
            'id': 70,
            'thread_id': 105775,
            'message': "hii",
            'created_at': "May 19, 2015",
            'datetime': 1432021227,
            'sender_id': 13,
        }
    },
    224199: { 
        0: {
            'id': 88,
            'thread_id': 224199,
            'message': "yessss...",
            'created_at': "May 20, 2015",
            'datetime': 1432306513,
            'sender_id': 14,
        },
        1: {
            'id': 75,
            'thread_id': 224199,
            'message': "hellowwww...",
            'created_at': "May 19, 2015",
            'datetime': 1432021227,
            'sender_id': 14,
        }
    },
    107917: { 
        0: {
            'id': 56,
            'thread_id': 107917,
            'message': "how r u??",
            'created_at': "May 16, 2015",
            'datetime': 1431792155,
            'sender_id': 14,
        },
        1: {
            'id': 30,
            'thread_id': 107917,
            'message': "hi.. i m fine.",
            'created_at': "May 6, 2015",
            'datetime': 1430920006,
            'sender_id': 14,
        },
        2: {
            'id': 30,
            'thread_id': 107917,
            'message': "hi!!!!..how r u??",
            'created_at': "May 6, 2015",
            'datetime': 1430920006,
            'sender_id': 14,
        }
    },
    378552: { 
        0: {
            'id': 108,
            'thread_id': 378552,
            'message': "hi",
            'created_at': "May 29, 2015",
            'datetime': 1432906923,
            'sender_id': 14,
        },
        1: {
            'id': 107,
            'thread_id': 378552,
            'message': "hi.",
            'created_at': "May 29, 2015",
            'datetime': 1432903194,
            'sender_id': 14,
        }
    }

};

Now, I need the output to be like this :

var inboxMessages = {
    378552: {
        0: {
            'id': 108,
            'thread_id': 378552,
            'message': "hi",
            'created_at': "May 29, 2015",
            'datetime': 1432906923,
            'sender_id': 14,
        },
        1: {
            'id': 107,
            'thread_id': 378552,
            'message': "hi.",
            'created_at': "May 29, 2015",
            'datetime': 1432903194,
            'sender_id': 14,
        }
    },
    224199: {
        0: {
            'id': 88,
            'thread_id': 224199,
            'message': "yessss...",
            'created_at': "May 20, 2015",
            'datetime': 1432306513,
            'sender_id': 14,
        },
        1: {
            'id': 75,
            'thread_id': 224199,
            'message': "hellowwww...",
            'created_at': "May 19, 2015",
            'datetime': 1432021227,
            'sender_id': 14,
        }
    },
    105775: {
        0: {
            'id': 85,
            'thread_id': 105775,
            'message': "hello",
            'created_at': "May 20, 2015",
            'datetime': 1432118191,
            'sender_id': 13,
        },
        1: {
            'id': 70,
            'thread_id': 105775,
            'message': "hii",
            'created_at': "May 19, 2015",
            'datetime': 1432021227,
            'sender_id': 13,
        }
    },
    107917: {
        0: {
            'id': 56,
            'thread_id': 107917,
            'message': "how r u??",
            'created_at': "May 16, 2015",
            'datetime': 1431792155,
            'sender_id': 14,
        },
        1: {
            'id': 30,
            'thread_id': 107917,
            'message': "hi.. i m fine.",
            'created_at': "May 6, 2015",
            'datetime': 1430920006,
            'sender_id': 14,
        },
        2: {
            'id': 30,
            'thread_id': 107917,
            'message': "hi!!!!..how r u??",
            'created_at': "May 6, 2015",
            'datetime': 1430920006,
            'sender_id': 14,
        }
    },
};

I'm not sure how to sort this in JS.

I want the most recent datetime for each thread to be at the top of the array.

Answer №1

Is this achieving your desired outcome?

//var inboxMessages = {... your input ...};

function convertMessages(inboxMessages) {
  var result = [];
  var threadIds = Object.keys(inboxMessages);
  var threadObj, threadArr, keys;

  for (var i=0, threadId; threadId=threadIds[i]; i++) {
      threadObj = inboxMessages[threadId];
      keys = Object.keys(threadObj);
      threadArr = [];
      result.push(threadArr);

      for (var j=0, key; key=keys[j]; j++) {
          threadArr.push(threadObj[key]);
      }

      threadArr.sort(function (a, b) {
        return (b.datetime - a.datetime);
      });
  }

  result.sort(function (a, b) {
    return (b[0].datetime - a[0].datetime);
  });

  return result;
}

function getThreadIds(threadArrays) {
  var threadIdArr = [];

  for (var i=0, threadArr; threadArr=threadArrays[i]; i++) {
    threadId = threadArr[0].threadId;
    threadIdArr.push(threadId);
  }

  return threadIdArr;
}

function findThreadById(threadId, threadIdArr, threadArrays) {
  var index = threadIdArr.indexOf(threadId);
  var threadArr;

  if (index < 0) {
    // no matching thread found
  } else {
    threadArr = threadArrays[index];
  }

  return threadArr;
}

var results = convertMessages(inboxMessages);
var threadIdArr = getThreadIds(results);
var recentThread = threadIdArr[0];
var recentMessage = results[0][0];
var specificThread = findThreadById(105775, threadIdArr, results);

console.log(results);
// sorted array of sorted arrays
console.log(threadIdArr);
// [378552, 224199, 105775, 107917]
console.log(recentThread);
// 378552
console.log(recentMessage);
/* {
  created_at: "May 29, 2015"
, datetime: 1432906923
, id: 108
, message: "hi"
, sender_id: 14
, thread_id: 378552
} */
console.log(specificThread);
// sorted array

Answer №2

The sorting of this array is already implemented in the server script using PHP. However, I noticed that when I retrieve the data via ajax and convert it to JSON, only the Chrome web browser sorts it in numeric order based on the thread_id in ascending order.

To address this issue, I decided to add an underscore _ before the thread_id on the server side so that it becomes _378552 and is treated as a string, preventing Chrome from automatically sorting it.

Once I have retrieved the data, I remove the underscore from the thread_id to access it properly. This workaround has successfully resolved the sorting issue, which seems to be specific to the Chrome browser.

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

Use PHP to redirect a webpage as an alternative to utilizing JavaScript

Recently, I encountered an issue where I created a form on inde1.php and utilized JavaScript to post data to login.php. My current goal is to redirect the user to another page once login.php has been successfully executed. Below is the JavaScript code on ...

Utilizing JavaScript to dynamically resize an element within a slide as soon as the slider transitions to the following slide

RESOLVED! ISSUE FIXED! While working on my personal website using WordPress and the Smart Slider 3 plugin, I encountered a problem with the positioning and size of an element in the second slide. Despite finding a tutorial explaining how to manually trigg ...

What is the best way to update my React components to switch from a dark theme to a light theme?

Currently, I am attempting to switch between a light and dark theme in React by utilizing a Switch component from material-ui. Strangely, the theme only toggles once from dark to light. If you want to take a look at the full code, you can find it on this C ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

Retrieving data from a multidimensional array using PHP

At this point in the program, my array can be in any state - either empty or containing arrays that have been inserted using a specific format. $productName=$_POST['productname']; if(!in_array($productName,$productArray)) { $productArray[]=a ...

Modify the tooltip of the selected item in an ng-repeat loop in AngularJS

Upon clicking an element, a function is executed which, upon successful completion, should change the tooltip of that specific element. Within an ngRepeat loop, I have multiple elements displaying the same tooltip. However, I only want to update the toolt ...

Adjusting firebugx.js for compatibility with Internet Explorer Developer Tools

The firebugx.js file (viewable at http://getfirebug.com/firebug/firebugx.js) is designed to detect the installation of Firebug by checking both !window.console and !console.firebug. However, this method does not account for the native console object in the ...

Grab the div, position it accurately, and initiate an ajax call

So many tasks on my plate, but let's prioritize. Within a <div class="showcase">, I have numerous <div class="game"> elements, each with an onclick="addpop('delpopup.php?id=something&pos=somethingelse&box=image')" Does ...

Getting data before the Router is loaded following authentication with Angular 2+ - A comprehensive guide

I'm hoping this isn't a repeat. Within my login component, I have a feature that allows users to log in, which calls a service and retrieves a Token. Upon successful login, the token is saved to localStorage. Subsequently, I use the getUserData ...

Uploading files with node.js and express

Currently, I am following the steps outlined in this tutorial: I have successfully followed the instructions until the section where they set up the routes without actually creating any views. The tutorial states: That's it, we have completed sett ...

Having trouble with the response function not functioning properly within an AJAX autocomplete

I have implemented an autocomplete feature using the jQuery UI plugin from http://jqueryui.com/autocomplete/#remote-jsonp. $("#city" ).autocomplete({ source: function( request, response ) { $.ajax({ url: 'index.php?secController= ...

Is it possible to create an online game using JavaScript?

Hey there, I'm interested in creating a simple online game that can be played in the browser. My main question is this: if I want two players to compete against each other online, can I achieve this by using HTML for the front-end and JavaScript for t ...

Creating a line graph using chart.js and JSON dataset

I'm working on plotting a line graph using a JSON response from my MongoDB, but I keep encountering an error that indicates something might be wrong with my code structure. Here's what I have attempted: myurl = "/api/humidity" $(function() { ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

Combine the values of identical keys from multiple objects in an array by utilizing the forEach method in JavaScript

I am currently working on refining a shopping basket function with Vue JS. One of the key features I need to implement is a subtotal calculation that multiplies the price and quantity values for each item and then combines them to create an overall subtota ...

I am continuously encountering an error message saying [$injector:modulerr] while working with AngularJS

I've been reviewing my JavaScript code thoroughly, but I can't seem to pinpoint any major issues. The error message I'm encountering is as follows: Uncaught Error: [$injector:modulerr] Failed to instantiate module careApp due to: Error: [$i ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...

Update the array in state by adding a new element using setState

How can I add a new element to an array using setState? Consider the following data: this.state = { items : [ { "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }, { "id" : "24", "parent" : "dwdw", "text" : "Root node" }, { "id" ...

troubleshooting problems with AJAX calls and routing in Angular

I am a beginner with Angular and I recently completed a tutorial on Single Page Application development using templates imported from PHP files, along with Resource and Route modules. Below is the JavaScript code from my project: (function(){ var app ...

What is the best way to populate a div with multiple other div elements?

My current project involves creating a sketchpad using jQuery for an Odin Project assignment. However, I have encountered an issue with filling the canvas (wrapper div) with pixels (pixel divs). The canvas does not populate correctly. Here is the link to m ...