Order JSON data by arranging ArrayList using JavaScript/jQuery

In the realm of JavaScript, I am working with data retrieved through AJAX that looks something like this:

data:{site: ["abc", "def", "gfr"], month: ["3", "2", "6"], value: ["10", "21", "1"]}

My task is to organize this data in ascending order based on the month key.

The desired outcome should look like this:

data: {site: ["def", "abc", "gfr"], month: ["2", "3", "6"], value: ["21", "10", "1"]}

I understand that I can sort an array using data.month.sort(), but this method only sorts the month array. Is there a way to sort all values based on the value of one particular key?

Answer №1

One common approach is to utilize the indices of a key array for sorting purposes, arranging the indices in a pattern that can then be applied to organize other arrays based on both the index and corresponding value from the key array.

Finally, the sorted array can be mapped back to its respective properties.

var data = { site: ["abc", "def", "gfr"], month: ["3", "2", "6"], value: ["10", "21", "1"] },
    array = data.month,
    indices = [...array.keys()].sort((a, b) => array[a] - array[b]);

Object.keys(data).forEach(k => data[k] = indices.map(i => data[k][i]));

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

Answer №2

To organize the month's keys (indices) based on their numerical value, you can use the sort method first. Then, utilize map to retrieve the data at each specific index in the array:

This arrangement sorts the months by their numerical value

const data = {site: ["abc", "def", "gfr"], month: ["3", "2", "6"], value: ["10", "21", "1"]}

const { site, month, value } = data;

const keys = [...month.keys()].sort((a,b) => month[a] - month[b])

const output = {
  site: keys.map(k => site[k]),
  month: keys.map(k => month[k]),
  value: keys.map(k => value[k]),
}

console.log(output)

Answer №3

Here is an alternative approach to achieve the same result (assuming site is the main focus):

const data = {site: ["xyz", "uvw", "mno"], month: ["9", "7", "4"], value: ["50", "15", "32"]}

const output = data.site
   .map((s, i) => ({site: s, month: data.month[i], value: data.value[i]}))
   .sort((a, b) => b.value - a.value)
   .reduce((acc, cur) => ({
         site: [...acc.site, cur.site],
         month: [...acc.month, cur.month], 
         value: [...acc.value, cur.value]
      }),
      {site: [], month: [], value: []});

console.log(output)

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

Iterate over JSON dates in JavaScript

Trying to utilize JavaScript in looping through a JSON file containing time periods (start date/time and end date/time) to determine if the current date/time falls within any of these periods. The provided code doesn't seem to be working as expected. ...

Instead of properly addressing the issue, the error message "Cannot read property 'password' of undefined" is being displayed

I'm currently working on creating a user login system using express js and dynamodb. However, I'm facing an issue where the system works fine when logging in with correct email and password, but fails to handle errors when using an incorrect emai ...

Having trouble with Vue and Vuex not returning the correct value in HTML?

I've implemented a navbar that displays specific menu items based on the user's role. Below is the simplified HTML code for the navbar: <v-speed-dial class="speed-dial-container contextual-text-menu" v-if="user && user. ...

Navbar collapse not functioning properly on HTML, CSS, and JavaScript

I have developed a CSS code snippet: .nav{ right: 0px; left: 0px; margin-top: 0px; margin-bottom:20px; height: 35px; text-align: center; background-color: red; z-index: 1; } .sticky { background: #000; text-align: center; ...

When array elements are assigned to an object's attribute, they are not preserved

In my code, I have created an instance of an array called shortFacilitiesArray to make modifications to an existing array by adding additional values. However, when I assign this instance array as the attribute of my object, all the data is unexpectedly lo ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Incorporating TypeScript with jQuery for efficient AJAX operations

I recently added jQuery typings to my TypeScript project. I am able to type $.ajax(...) without encountering any compile errors in VS Code. However, when I test it on localhost, I receive an error stating that "$ is not defined." In an attempt to address t ...

jQuery with various onClick event listeners

I have successfully implemented a calendar feature with a "More" button on each day to display additional events if there are more than three. However, I am facing an issue where clicking the button triggers the dropdown for all days instead of just the se ...

Implementing features similar to Facebook comments using ASP.NET

I'm currently working on a project to create a blog platform using ASP.NET. One of the key features I'd like to include is the ability for users to add comments. My goal is to replicate the functionality of Facebook when it comes to adding and d ...

Conceal button divider on pager in Jqgrid

Within my grid setup, there are 3 buttons placed in the pager section: 'Refresh', 'Constution', and 'Developed'. These buttons are separated by two vertical navSeparators. Upon grid load, the 'Developed' button is hi ...

The radio button that disables other inputs only functions correctly for a single element when using Query Selector, but does not work with Query

I have attempted to develop a form section that is disabled when the user selects option A and enabled when they choose option B. document.getElementById('delivery').onclick = function() { var disabled = document.querySelectorAll(".dis ...

Choose an option from a dropdown menu and assign it to a JavaScript variable

Is it possible to store the selected option from a dropdown list as a JavaScript variable, even when new Ajax content is loaded on the page? Below is a simple form code example: <form name="searchLocations" method="POST"> <select name="l ...

Filtering arrays using Vue.js

I have developed a sample e-commerce website to showcase various products to potential customers. The website boasts features like filters, search functionality, and sorting options to enhance the user experience. However, I've encountered an issue sp ...

The interactivity of data-ng-click in HTML is not functioning as expected

I need help with implementing the data-ng-click functionality for a dynamically created button. Can someone assist me with this? var table = document.getElementById("dashboard"); for( var i = 0; i < $scope.namesOfMembers.length; i++ ){ var row = t ...

What techniques can be employed to create a fully operational web application using AngularJS?

I have taken on the challenge of understanding AngularJS by creating a webapp. Within my Eclipse environment, I am working with 4 files: main.js, index.html, view1.js, and view2.html. Currently, I can get index.html to load when Tomcat is running. Embedd ...

Implement an event listener on the final element of a webpage utilizing querySelector

I need help with a password security check feature that changes field borders to green or red based on certain conditions. Despite successfully implementing it, the JavaScript code only selects the first field (nickname) instead of the last one. I've ...

Passing a Scope to ES6 Template Literals: How to Ensure they are Interpreted Correctly?

I've recently started utilizing template literals to create an error generator. Although I have functional code, I find myself having to define the list of potential errors within the constructor scope, and this is not ideal for me. Is there a way t ...

instructions on invoking a function within the knockout $.getJSON() operation

I am currently experimenting with a basic knockout script (still in the learning process). $.getJSON(clientUrl + "/list/" + 1, function (data) { var viewModel = { clients: ko.observableArray(data) }; ko.applyBindings(viewModel); }); The initial arg ...

"Using Node.js to create a simulated mobile environment: a step-by-step guide

I am seeking a way to replicate the functionalities of a mobile browser using Node.js. This means that all mobile browser features should be accessible on the client-side, even if they are simulated. The goal is for webpages to believe they are being load ...

What is the process of transferring information from a form to mongodb?

I have created a nodejs project with the following structure: https://i.stack.imgur.com/JiMmd.png api.js contains: const express = require('express'); const router = express.Router(); const add = require('../model/myModel'); router.g ...