Arranging a javascript object by organizing an array as a value

Looking to organize a JavaScript Object structured as key:pair, where the pair consists of an array with 2 timestamp values. The goal is to arrange the elements so that those with the smallest numbers (earliest times) are shown first.

For instance, consider this object:

{"21_2":[1409158800,1409160000],"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600]}

In this scenario, the desired sorted object would be:

{"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600],"21_2":[1409158800,1409160000]}

To achieve this, the sort() function will need to be utilized for the arrays. However, accessing these values within the object may be a challenge due to the non-integer nature of the object key caused by the underscore.

While exploring potential solutions, I came across this resource: Sort Complex Array of Arrays by value within. Despite this, I have yet to successfully adapt it to my specific scenario. Any assistance on this matter would be highly appreciated.

Answer №1

If you want to restructure your data, consider the following approach:

var sampleArray = [{
        "id" : "21_2" // unique identifier
        "timeStamps" : [1409158800,1409160000]
    }, {
        "id" : "20_1"
        "timeStamps" : [1409148000,1409149200]
    }];

Once you have updated the structure, you can easily sort it using the array sort method:

sampleArray.sort(function(a, b){
    // Comparison logic here:
    return a.timeStamps[0] - b.timeStamps[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

Combining a JavaScript NPM project with Spring Boot Integration

Recently, I built a frontend application in React.js using NPM and utilized IntelliJ IDEA as my IDE for development. Additionally, I have set up a backend system using Spring Boot, which was also developed in IntelliJ IDEA separately. My current goal is t ...

What causes one CSS file's properties to be inherited by another CSS file in a React application?

I'm puzzled as to why my hero section file seems to be adopting the styling from the navbar CSS file. I do understand that the index.css file sets properties for the entire app, but in my case, I have separate CSS files for different components instea ...

Generating unique identifiers for ng-model in AngularJS

Issue - ng-model is not generating dynamically. I have dynamic input boxes and I am attempting to create ng-model dynamically like test[1], test[2], etc. However, when inspecting the form with Firebug, all input elements only show - test[shiftnumber]. HT ...

Fully responsive header designed for optimal experience at any screen height

I am facing issues with the header and cannot seem to find a solution. My goal is to make the header span 100% of the window screen height. I need a responsive header that adjusts to 100% height, and when resizing for a smaller viewport, nothing should sho ...

How can I pass the value of a variable from one Vue.js 2 component to another?

Here is how I have structured my view: <div class="row"> <div class="col-md-3"> <search-filter-view ...></search-filter-view> </div> <div class="col-md-9"> <search-result-view ...></ ...

Challenges when using deep linking to URL with AngularJS ui-router

Recently, I encountered an issue after restructuring the folder organization of my AngularJS application. Although I believe this might be a distraction from the root cause, I moved a section of functionality to its own directory for better organization. A ...

Issue with mouseout gap in Microsoft Edge when using the <select> element

A noticeable gap appears in Microsoft Edge between the <select> menu and its options when expanding the menu, as shown here: https://i.stack.imgur.com/SprJ2.png This particular issue can cause problems with the mouseout event due to inconsistent be ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

Utilizing database information for interactive objects in Three.js: A step-by-step guide

I need to display specific text data for each object based on database entries in my project. However, despite creating a cube for each entry in the database, I'm encountering issues with undefined data. It seems like my code should work, but it' ...

Tips for working with elements in WebDriver that are created dynamically by JavaScript

As a novice in automation using Java and WebDriver, I find myself facing a particular issue: Browse for a specific customer Select a new customer type from a dropdown menu Click on the Save button Outcome: Upon trying to change the customer, a message p ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

Transfer information from an Express route to a function exported from a Node module

I'm new to using node.js and I've been told that I need to use middleware, but I'm having trouble understanding its purpose and the proper way to implement it. I have data that is being sent from my view to an express route. ROUTE - route.j ...

Implement Material UI TextField to ensure all required fields are properly formatted

Looking to customize the underline border color of TextFields marked as mandatory within a form using react-hooks-form. I understand that I need to define a style for these fields, but I'm struggling with where to start... This is the current code s ...

Attempting to extract the desired aggregations from a two-dimensional JSON array

Looking to parse through this JSON 2D array (snapshot data example below) to calculate the total cases and deaths for each date, disregarding the state column. While achievable in SQL, it poses a challenge in JavaScript. Ultimately, the summarized data wi ...

Generating Dynamic Object Keys following Array Mapping

I have a vision of creating a sophisticated data structure resembling the configuration below: slots: { 'slot_1': { id: 'slot_1', associatedCard: {} }, 'slot_2': { id: 'slot_2& ...

Best practices for integrating Vuex with Vuelidation

Currently, I am developing a Vue front end for an application that necessitates storing all form data locally before sending it to the backend in case of any network connectivity issues. To achieve this, I am using Vuex to manage and retain all the necessa ...

Arraylist accessing elements by their index position

We currently have an object containing an x coordinate and are attempting to determine which object stored in our "save" arraylist is closest to a view whose coordinates come from getLocationInWindow(), stored in an array. for (int i=0; i<save.size(); ...

Determining the scroll position of a JQuery Mobile collapsible set upon expansion

I am utilizing jQueryMobile (v1.4.0) collapsible set / accordions to showcase a list of elements along with their content, which can be seen in this jsFiddle. <div id="List" data-role="collapsible-set"> <div data-role="collapsible" data-conte ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...