Arrange one array while ensuring the order of the other two arrays remains consistent

data = {
    "age": [41, 21, 88],
    "name": ["Rob", "Tom", "Susan"],
    "color": ["Red", "Blue", "Orange"]
}

Is there a way to effectively sort the data in these records based on the values of one specific array while maintaining the original data structure? I have already tried using the sort() function but it seems to break the connection between the different arrays.

data = {
    "age": [21, 41, 88],
    "name": ["Tom", "Rob", "Susan"],
    "color": ["Blue", "Red", "Orange"]
}

Answer №1

To maintain the arrays separately, you can obtain the index ordering by first sorting the age array and then arranging each array based on that order:

let info = {
  "age": [41, 21, 88],
  "name": ["Rob", "Tom", "Susan"],
  "color": ["Red", "Blue", "Orange"]
};

let indexOrder = info.age
  .map((a, i) => [a, i])
  .sort((a, b) => a[0] - b[0])
  .map(a => a[1]);

for (let key in info) {
  info[key] = indexOrder.map(i => info[key][i]);
}

console.log(info);

Answer №2

It is highly recommended to store such information in a true object-oriented manner, as demonstrated below:

[
  {
    "age": 33,
    "name": "Emily",
    "color": "Green"
  },
  {
    "age": 52,
    "name": "Jack",
    "color": "Yellow"
  },
  {
    "age": 19,
    "name": "Alice",
    "color": "Purple"
  }
]

Although it may seem verbose, this method is superior as the related properties are now tightly linked together.

Sorting can be achieved using the following code snippet:

data.sort((a, b) => a.age - b.age)

Answer №3

One way to organize and arrange your data is by restructuring it:

var information = {
  "id": [123, 456, 789],
  "name": ["Alice", "Bob", "Eve"],
  "location": ["New York", "Los Angeles", "Chicago"]
};
information.id.map(function(y, z) {
  return {
    id: information.id[z],
    name: information.name[z],
    location: information.location[z]
  };
}).sort(function(c, d) {
  // You can customize the sorting order based on the values
  return c.id - d.id;
}).forEach(function(p, q) {
  information.id[q] = p.id;
  information.name[q] = p.name;
  information.location[q] = p.location;
});
console.log(information);

Answer №4

information = {
    "age": [47, 29, 64],
    "name": ["Sara", "Peter", "Lily"],
    "color": ["Green", "Yellow", "Purple"]
}
var organizeData = info => {
     var dataArr = []
     info.age.forEach(
     (value, index) => {
        dataArr.push(
            {
                age: value, 
                name: info.name[index],
                color: info.color[index]
            }
         )
     })
     dataArr.sort((a, b) => a.age - b.age)
     console.log(info)
     info = {
          age: [],
          name: [],
          color: []
     }
     dataArr.forEach(value => {
          info.age.push(value.age)
          info.name.push(value.name)
          info.color.push(value.color)
     })
     console.log(info)
}
organizeData(information)

Exactly as presented above. Trincot's answer should be followed.

Answer №5

Your input contains separate values that should be combined into one object like this:

{
  "age": 41,
  "name": "Rob",
  "color": "Red"
}

One approach is to use the Array.prototype.map function to create the object, then sort it by age using Array.prototype.sort, and finally reassemble the desired output with Array.prototype.reduce.

I suggest reconsidering how the related data is stored.

let data = { "age": [41, 21, 88], "name": ["Rob", "Tom", "Susan"], "color": ["Red", "Blue", "Orange"]},
    obj = data.age.map((age, i) => ({age, name: data.name[i], color: data.color[i]})),
    result = obj.sort(({age: a}, {age: b}) => a - b).reduce((a, c) => {
      a.age.push(c.age);
      a.color.push(c.color);
      a.name.push(c.name);
      return a;
    }, {age: [], color: [], name: []});

console.log(result);
.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

Fix the improperly formatted JSON data

I'm currently utilizing $.ajax to retrieve JSON data from a REST API. The challenge arises when the responseText I receive is malformed, resulting in a SyntaxError: JSON.parse: unexpected non-whitespace character error. Upon investigation, it appear ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...

Dealing with Error TS2769 in Visual Studio Code when passing props to a custom component in Vue 2 with Typescript

I've encountered an issue with a Vue JS component that involves passing a custom prop. I am utilizing the Vue Options API without utilizing the class component syntax. Whenever I pass ANY prop to my custom component the-header, I receive an error sta ...

Having issues with Thymeleaf template not functioning properly when using inline JavaScript

I've encountered an issue when attempting to extract my function into a script within HTML. When written as shown below, it works perfectly: <input type="text" id="myInput" onkeypress="return confirm('Are you sure you want to delete ...

Encountered an error in React JS and Axios when attempting to select a form: "Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'."

I'm encountering an issue while attempting to send FormData using Axios within a React JS application. The form should include both text inputs and multiple file uploads. However, when I tried to select the form with querySelector, it doesn't app ...

"Enhance Your Form with JQuery Date Selector for Multiple Input

Using JQuery and ASP.Net C#3.0. Here is the script I am working with: <script> $(document).ready(function () { $("[id$=txtHiddenDate]").datepicker({ showOn: "button", buttonImage: "../../images/calendar-icon.gif", ...

How can I loop through map.entities in Bing Maps v7?

I am working on adding multiple polylines to my map. However, after some logic processing, I need to loop through the map.entities collection to retrieve all the polylines that I have added. var polylineN = new Microsoft.Maps.Polyline(loc); map.entities.p ...

Mixing up jQuery's Deferred, jsDeferred, and the concept of deferring in coding can be a common source of confusion

I recently downloaded a library called jsdeferred in hopes of resolving some code-flow issues I've been facing. However, I'm finding the examples and documentation to be a bit unclear. In my quest for clarity, I also discovered that jQuery offers ...

When attempting to execute a promise within a test, encountering a 400 error in a NodeJS environment

I recently started using Contentful, a new JavaScript library for creating static websites. My goal is to incorporate it into my Node.js project. To achieve this, I developed an app file called getContent.js: 'use strict'; var contentful = req ...

How do I show a variable within my react-native render function?

I attempted to showcase information fetched by a function in my React Native rendering application. Even though I successfully retrieved the data, I am encountering issues when trying to display it on the app. This is the snippet of my code: import Reac ...

Is Object Cloning the Solution for Creating Multiple Views in THREE.js with Multiple Canvasses? Considerations to Keep in Mind

While seeking advice on object picking from small three.js viewport, I learned a technique for mouse-picking objects from a smaller canvas. Now, I am looking to showcase N different views of the same scene while still being able to perform object picking. ...

What is the correct way to establish and terminate a MongoDB connection in a Node.js application?

Hey everyone, I have a piece of code at this link (https://github.com/MrRav3n/Angular-Marketplace/blob/master/server.js) and I'm curious if I am properly starting and ending my database connection. Should I connect and end the db connection in every a ...

Wordpress problem with Bootstrap JavaScript code involving data-toggle="collapse"

Currently facing an issue with my project. This is my first attempt at creating a WordPress blog, inspired by the HTML site www.humantools.com.mx and building a blog for it at www.humantools.com.mx/blog. There's a strange problem: when logged in, the ...

What is the method for comparing a value in TypeScript that does not match a given value?

I am new to scripting languages and encountered an issue while using enums with if-else statements in TypeScript. To work around this problem, I have decided to use switch-case instead of if-else conditions. Despite trying !== and !===, they do not seem t ...

Adjusting Classes in JavaScript with jQuery

I need to create a feature that changes the state of a button from active to inactive based on user input, using Bootstrap. Ultimately, I am working towards finding an intuitive way to validate form input so that the submit button can be pressed for PHP pr ...

Unable to assign a className to a personalized React component - troubleshooting needed!

I have a component that relies on another component. I am trying to pass CSS positioning from the outer component to the inner one by using the following code: import OptionsMenu from './OptionsMenu' import { withStyles } from 'material-ui/ ...

Utilizing jQuery's CSS function to adjust the "left" margin of multiple div elements

I am working on creating a menu bar that will be displayed at the top of my page. Each section of the menu will be a link to a different part of the page. $(document).ready(function() { var w = window.innerWidth || document.documentElement.clientWid ...

50% greater than the highest of the other values

I'm a beginner when it comes to JavaScript and I need help setting a maximum value of 50% of the selling price. Can someone offer guidance? The fields I have are called "sale_price" and "discount". click here for image description What is the best ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

What is the best way to transform an object into a list using javascript?

Can someone help me transform this object into a list in an ExpressJS view (using EJS)? {https://ae01.alicdn.com/kf/HTB12Xa4ipGWBuNjy0Fbq6z4sXXa3/Mickey-Mouse-Microwave-Glove-Potholder-Bakeware-Blue-and-White-100-Cotton-Oven-Mitts-and-Potholder-mat.jpg,ht ...