A function with a specific name for sorting a multidimensional object based on a specified sub-key's value, without anonymity

My data consists of a collection of objects, not an array:

var people = {};
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'};
people['Jen'] = {date: 147, last: 'Roberts'};

In contrast to a general sorting question, I need to specifically indicate which sub-key's value should be used for sorting, in this case: date. To simplify matters, I've omitted the first seven digits of the dates as they are irrelevant.

Once sorted, the object should arrange its elements based on the values of the date key like so:

people['Jen'] = {date: 147, last: 'Roberts'}; // 147 is the lowest/first value
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'}; // 947 is the highest/last value

I am aiming to create a named, non-anonymous function that can be reused, requiring two obvious parameters: the object and the key by which the sorting will be done. Despite several attempts, the following approach has not yet yielded successful results:

function array_sort_by_values(o, k)
{
 return Object.entries(o).sort().reduce(function (result, key)
 {
  //console.log(result,key);
  result[key][k] = o[key][k]; return result;
 }, {});
}
  • I cannot utilize o.sort since it pertains to arrays rather than objects, despite JavaScript asserting that everything is an object without true "arrays".
  • The ability to specify the key name is crucial for me due to its use across different scenarios where sorting is needed. What aspect am I overlooking in my implementation?
  • No external frameworks or libraries are acceptable in this solution.

Answer №1

Have you considered converting the object to an array, sorting it, and then converting it back?

var people = {};
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'};
people['Jen'] = {date: 147, last: 'Roberts'};
console.log(Object.fromEntries(Object.entries(people).sort((a,b) => {
    return a[1].date - b[1].date
  })))

var people = {};
people['Zanny'] = {date: 447, last: 'Smith'};
people['Nancy'] = {date: 947, last: 'William'};
people['Jen'] = {date: 147, last: 'Roberts'};
console.log(Object.fromEntries(Object.entries(people).sort(([,a],[,b]) => {
    return a.date - b.date
  })))

You can also achieve this with a named function:

function array_sort_by_values(o, k)
{
 return Object.fromEntries(Object.entries(o).sort((a,b) => {return a[1][k] - b[1][k]}));
}

To apply the changes to the object, you need to reassign it:

people = array_sort_by_values(people, 'date');
console.log(people);

array_sort_by_values(people, 'last')
console.log(people);

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

The issue of req.file being consistently undefined in Node.js multer

I am having issues trying to upload a file using multer because the req.file is always undefined and the destination folder remains empty: Server: var express = require('express'); var multer = require('multer') var app = express(); ...

What could be the reason for my button to update only at the completion of the "each" loop?

Is there a way to update the button text before the loop, so that users can receive feedback while it's running? Currently, the text only updates after the loop has completed. In my scenario, the button displays "Updating please wait..." after the lo ...

Issue encountered while trying to exhibit jpg image content from server side on html

I am attempting to display an image from server-side data using an Ajax call. The data stored on the server looks something like this: "ÿØÿàJFIFÿÛC4­¶¸UOHlʵcBò)3¹_È'I4~&éüÿ§Ú<ã©ã4>'Øù¿ÇÄmËCÈgÚsZ¥ë" Upo ...

When initializing a new Date object with a number versus a string, the resulting values will vary

As I delve deeper into JavaScript, I stumbled upon an interesting quirk in its behavior. When creating date objects like this: var stack = new Date(1404187200000) // 07-01-2014 var overflow = new Date('07-01-2014') I noticed that when comparin ...

The issue persists with UIkit modal element remaining in the DOM even after the parent component in Vue.js is destroyed

In my Vue app, I am utilizing the UIKit modal. UIkit.modal(element).show(); // This adds the class uk-open and sets style to display:block UIkit.modal(element).hide(); When I hide the modal, it simply removes the class uk-open and the inline style of dis ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

The ion-slide-box does not function properly the first time the HTML page is loaded

Upon loading the page, my ion-slide-box does not function correctly. However, if I refresh the page, it works as expected. I have tried referring to some links but have been unable to resolve this issue on my own. Any assistance would be greatly appreciate ...

Falling rain animation in JavaScript

I'm a beginner in the world of JavaScript and I'm trying to create a div on a webpage with a rain effect. I've managed to generate random blue points within the div, but I'm struggling to make them move downwards. Here's the code I ...

ASP.NET repeater causing jQuery scrollTop to malfunction after first use

I am facing a peculiar issue where I need to scroll through repeater items in a RadWindow using arrow keys in an ASP.NET application. Below is the code snippet: function isScrolledIntoView(elem) { var docViewTop; var docViewBottom ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

Having trouble displaying specific images on React Native, how can I resolve this issue?

I am currently developing a weather application that retrieves weather information and displays it using ForecastItem components. However, I have noticed that some of the components do not display the weather image randomly. On the Home screen, I use the ...

end the node.js automated testing process

I'm currently using Jasmine and Zombie JS to create automated tests. I have integrated Drone.io for Continuous Integration, and the tests are executing successfully. However, there seems to be an issue where after passing the tests, the process does n ...

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

What is the best practice for accessing specific components of JSON values that are delimited by colons?

When working with an API that returns a JSON containing strings separated by colons, such as: { "id": "test:something:69874354", "whatever": "maybe" } It may be necessary to extract specific values from these strings. For example, in the given JSON s ...

Struggling to understand the javascript snippet "requiring the passport file and passing in passport as a parameter."

I am still learning the ropes of javascript and currently working on a basic login restful api using the passport middleware. I understand that when I use require('xxxxx'); I am importing a module for use. While researching online, I came across ...

How to handle an unexpected token error when using a function within another function in

I'm encountering an issue where the function below is placed above my render function. It doesn't seem to allow me to nest a function within another function. Can you help me identify what's causing this problem? onSelected(i){ this.st ...

The success function of the Ajax request remains untouched by the response

My ajax call isn't triggering the success:function(resp){ ...} Despite receiving a response status of 200 and a non-null Json response. This is my ajax setup: $.ajax({ url: '/url/', type: 'GET', data: { pass_ ...

Ajax undoes any modifications enacted by JavaScript

When using ajax, I trigger an OnTextChangedEvent. Before this event occurs, there is a Javascript function that validates the input field and displays text based on its validity. However, once the Ajax is executed, it resets any changes made by the Javascr ...

Streamline the process of sorting through 2 arrays

Is there a more concise and elegant way to achieve the same functionality as my current method? I am looking for a shorter solution to create an array of items that haven't been used in the form previously, which are then used to populate a select dro ...