Organize and arrange all arrays within an object using JavaScript/TypeScript

Is there a more elegant way to sort every array in this object? Currently, I am doing it as shown below:

this.userInfo = {
    Interests: [],
    Websites: [],
    Games: [],
    Locations: [],
    Companies: [],
    Projects: [],
    Schools: [],
    Studies: []
};


this.userInfo.Interests.sort();
this.userInfo.Websites.sort();
this.userInfo.Games.sort();
this.userInfo.Locations.sort();
this.userInfo.Companies.sort();
this.userInfo.Projects.sort();
this.userInfo.Schools.sort();
this.userInfo.Studies.sort();

Open to suggestions for optimization?

Answer №1

To retrieve all the direct property names of an array, you can utilize Object.keys. Then, you can loop through these keys using Array#forEach:

Object.keys(this.dataInfo).forEach(function(property) {
  this.dataInfo[property].sort(function(x, y) {
    // Custom sorting algorithm goes here
  });
});

Answer №2

Give this a try, it may be helpful:

this.userData = {
  Hobbies: [1, 4, 3, 2],
  Websites: [1, 4, 3, 2],
  Games: [1, 4, 3, 2],
  Cities: [1, 4, 3, 2],
  Companies: [1, 4, 3, 2],
  Projects: [1, 4, 3, 2],
  Universities: [1, 4, 3, 2],
  Majors: [1, 4, 3, 2]
};

for (var category in this.userData) {
  console.log(this.userData[category].sort());
}

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

Snowflake's innovative solution for converting semi-structured data into a flat format without the need for key-value

I currently have JSON data stored in an array format within Snowflake, structured as: [[col1, col2, col3, col4], [a1, a2, a3, a4], [b1, b2, b3, b4], [c1, c2, c3, c4]... etc] This array is loaded into Snowflake as a table named data_table, with 1 row (rep ...

Please enter a string and I will locate it within an array. If found, I will provide you with information about that string as a fact

I have a specific challenge I need help with. I have a pre-defined array that contains country names and corresponding facts about each country. What I am trying to achieve is to check if the user-inputted word matches any of the countries in my array, a ...

Exploring the intricacies of nested objects

I am currently developing an API that retrieves data from an external source. After processing the business logic, I end up with the following response: { data: [ { BTC: { USD: 46389.84, RUB: 3406131.15, EUR: 39472.76, ...

Unexpected issue encountered for identifiers beginning with a numerical digit

Is it possible to select an element from a page with an id that begins with a number? $('#3|assets_main|ast_module|start-iso-date') Upon attempting to do so, the following error occurs: Uncaught Error: Syntax error, unrecognized expression: ...

Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class? class Car { wheels: number; model: string; } const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'}; const goodCar = filterUnwant ...

When attempting to modify an element in an array within a state-managed object, the input field loses focus

In attempting to address my issue, I have crafted what I believe to be the most concise code example. The main goal is to display a table on the page populated with exercise data retrieved from a database. This data is then assigned to an array of objects ...

Run a script following the completion of loading data through ajax within a loop

boot_sections = ["123625","113231","11232","113216", ..... ]; for (var k in boot_sections) { $.get('/load?sectionId=' + boot_sections[k], function(data) { $('#sections').append(data); }); } This is the spot where I loa ...

Identifying the presence of a tag in Vue.js

Check out my Code: <template v-for="day in getMonthLength()" > <td :id='notempty' v-for="dataa in data" v-if="dataa.employee_id === employee.id"> <input type="numb ...

The server tag is displaying an error due to incorrect formatting in the hyperlink data-binding section

I'm currently facing an issue with the formatting of my hyperlink. The text part of the hyperlink is working fine, which leads me to believe that the problem lies within the JavaScript. However, I am unable to pinpoint the exact issue. <asp:Templa ...

Utilize selenium IDE to retrieve a specific portion of text and save it as a variable

I am trying to figure out how to extract the number 694575 from a text using Selenium Ide and store it in a variable for future use. Here is the text I am working with: <div class="loginBoxTitle">Edit Exhibition Centre - 694575, Exhibition Center1&l ...

Is there a way to collapse an element by clicking either the content inside the div or the button within the div?

Is there a way to make a button within a newly activated div close it? The existing code seems to have issues with this functionality, and adding new rules or functions has not solved the problem. Any assistance with fixing this issue using vanilla JavaScr ...

What sets apart the concepts of Boolean and boolean when it comes to Typescript?

I would like to understand the distinction between Boolean and boolean in Typescript. Can anyone provide an explanation? ...

How can I incorporate multiple JSX files into plain HTML without using npm?

I have a question regarding importing JSX files in an HTML file without using npm and directly running it with LiveServer. I have two files, index.js and app.jsx, that I want to connect within my index.html script. How can I achieve this? Code: index.html ...

Is your Javascript code for the Donate button functioning properly in Chrome but encountering issues in Internet Explorer and Firefox? See my attached code for troubleshooting

My code is working fine on Chrome without any errors, but it is not functioning properly on Mozilla and IE. Here is the script: <script type="text/javascript> function Donate() { var myform = document.createElement("form"); myform.ac ...

A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this: //main.js import "./vue-extensions/prototypes"; ...

What is the correct way to end this jQuery statement?

I've been working on this for about 6 hours now. I ran it through multiple Lint tools and various other online tests, but I just can't seem to get the statement below to close properly. There's a persistent error showing up on the last line ...

Angular code is failing to send a signal to the server following a $http.post request

I've been using angular for about a week now and I've been struggling to solve this issue. I have a service that wraps around $http because multiple controllers make calls to the same URL. On one particular page, there is a lot of server-side bus ...

Ajax dependent dropdown is failing to load properly on the live server

My dropdown menus for country, state, and city are chained to each other, where the state options depend on the selected country and the city options depend on the selected state. While this functionality works perfectly on my local server, it's not w ...

What is causing the error message of "prop id does not match the rendered server output" to appear on my screen?

https://i.stack.imgur.com/VOLDT.png I've been working on a nextjs redux project and I keep running into this error whenever I refresh my page. Despite searching for a solution, I haven't been able to resolve it. The official next js blog suggest ...

Is my Socket.io application consuming excessive bandwidth? What might be causing this issue?

Upon reviewing my AWS billing report, I noticed an excessive data transfer of 495.385 GB on my socket.io application running on the EC2 instance. This amount seems too high for a small experimental website like mine. Could this be due to inefficient code i ...