Organize a JavaScript object based on key order within an array using a non-indexed array key

I am currently dealing with an issue where my array does not have traditional numerical indexes (0, 1, 2, 3, etc.), but rather uses IDs like 0654, 3423, 7543, and so on. For example:

var obj = {};
obj["0654"] = { "Name" : "Tony" };
obj["3423"] = { "Name" : "Fred" };
obj["7543"] = { "Name" : "Dave" };

I am trying to find a way to sort these objects by their "Name" key, but I keep encountering an error stating that it is not a function. I am using the following sorting code:

Array.prototype.sortByProp = function(p){
    return this.sort(function(a,b){
        return (a[p].toLowerCase() > b[p].toLowerCase()) ? 1 : (a[p].toLowerCase() < b[p].toLowerCase()) ? -1 : 0;
    });
}

When attempting to run the sorting function with:

obj.sortByProp("Name");

Any advice or suggestions on the best approach would be greatly appreciated. If this question has been asked before, please direct me accordingly as my search for a solution to this specific scenario has so far been unsuccessful. Additionally, understanding why this method is not working will help me gain a better grasp of working with objects.

Answer №1

Lodash is a powerful library to enhance your code!

_.sortBy(collection, 'category');

Give it a shot!

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

Embedded URL in dynamically created AJAX text

I created a search field that uses ajax/jquery to generate a list of users. Result: <li class="list-group-item"> <span class="glyphicon glyphicon-user"></span> <span class="badge addUserToGroup" data-user="{{ user.getId }}"&g ...

Insert a new key-value pair into a PHP associative array retrieved from a database

Here's how the DB is currently set up: include 'php/DbConnect.php'; $sql = $mysqli->query( "SELECT t.*, v.* FROM task t INNER JOIN vocabtask vt ON (t.id = vt.taskid) INNER JOIN vocab v ON (v.id = vt.vocabid) WHERE vt.taskid = 1" ...

Error: Unable to execute _this2.setState in react - potential problem with binding

I am completely new to utilizing react, and I have been encountering difficulties in pinpointing the root cause of this error that keeps popping up in the chrome console bundle.js:15316 Uncaught (in promise) TypeError: _this2.setState is not a function M ...

Difficulty encountered when attempting to extract a username with multiple spaces using the .split() method in Discord.js with NodeJS

Currently, I am enhancing a feature in my Discord Bot that fetches the League of Legends statistics of a player by using the command !lolid [enter_username_here] in a Discord chat room. The function works smoothly for usernames with just one word; however, ...

Guide to comparing two TSX elements in a React + TSX environment

I am facing difficulties in comparing two React TSX elements. Despite being new to both React and TSX, I have tried copying and pasting the exact elements for comparison but it doesn't seem to work. Can you guide me on what might be causing this issue ...

Enhance your comment editing experience with ReactJS!

Currently, I am delving into the world of ReactJS and attempting to understand how to modify comments within it. To gain insight, I have been diligently following this particular tutorial. Various potential solutions are swirling in my mind: Opting for ...

Having issues with accessing data from Informix database in PHP due to an undefined index?

I am encountering the following error multiple times per row: Notice: Undefined index: enviopre in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 34 Notice: Undefined index: enviofra in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 35 Notice: Undef ...

managing browser pop-ups in selenium with the help of JavaScript

My objective is to input a username and password in the popup box that shows up every time the page loads. I am utilizing selenium for this purpose, and unfortunately, all attempts I've made so far have been unsuccessful. I attempted to use the follo ...

PHP: How can items in an array be best identified?

Is there a preferable method to manually mark certain entries in an array (highlighting specific items in the database as needed) so they can be recognized and acted upon differently? I am curious about what the most efficient and fastest approach would be ...

JavaScript causing Selenium/Beautiful Soup scraper to crash after parsing only one page

As I try to scrape data on food seasonality from the Seasonal Food Guide, I've encountered a roadblock. The URL structure of the website is quite simple: Using Selenium and Beautiful Soup, I've managed to successfully extract seasonality informa ...

A guide on iterating through an array to generate a new array within the loop, filled with elements from the original array

Hey there! I'm currently working on a game and have run into a roadblock with arrays and loops in PHP. Specifically, I need to create a function that generates a stack of crystal IDs based on a given size and ratio. The ratio refers to the proportion ...

What is the method to detect the presence of any value from one array in another array using AngularJS?

In my AngularJS factory method, I am creating a permission function to check the user's role. If the user object contains the specified role, the result should be true; otherwise, it should return false. Here is an example of my user object: administ ...

Master the ins and outs of working with Angular and Webpack on

Encountering issues with the webpack-angular tutorial from egghead.io during the "ES6 with Babel" step. Requesting assistance in resolving the problem. Stuck at this specific step while following the tutorial: Error message in Chrome devTools: ........ ...

Switching visual representation that appears upon clicking the dropdown menu

Issue with Duplicating Dropdown and Image Change const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function handleChange() { let imgsrc = this.getAttribute("data-value ...

The correct method for implementing server-side rendering with JavaScript

My website consists of multiple pages and utilizes React as a widget toolkit, with different bundles on each page. I am facing an issue where some widget state persists within a login session, and when the user revisits the page, the components should relo ...

Discovering a specific URL link element within the DOM using webdriver.io

I am currently utilizing webdriver io for conducting tests on a webpage. I am in need of verifying the existence of an element with a specific href on the page. I have attempted to achieve this using the following snippet var client = webdriverio.remote ...

Is it permissible to assign the same element as a child to multiple parent elements in jQuery?

Imagine you have the following HTML structure: <div id="first"></div> <div id="second"></div> Now, if you use JavaScript and JQuery to perform the following actions: var $child = $("<span id='child'>Hello</span ...

Unable to run a query in PHP that executes successfully in phpMyAdmin

I'm currently attempting to remove rows from a table using the following code: $query = "Delete from usertour where tourID = $idnum and name LIKE '%$session%' "; However, even when the idnum and session are correct, the row is not being ...

Checking the Ajax request with an if statement

$("#Submit").click(function(event){ event.preventDefault(); var th = '<tr><th>' + "Business" +'</th><th>' + "Address"+ '</th><th>'+ "Rating" + '</th><th>' + "Da ...

How can conditional types be implemented with React Select?

I am working on enhancing a wrapper for React-select by adding the capability to select multiple options My onChange prop is defined as: onChange: ( newValue: SingleValue<Option>, actionMeta: ActionMeta<Option>, ) => void Howev ...