The functions orderBy() and sortBy() in the _lodash library are designed to organize objects based on their 'weight' property

Upon reflection, I am sharing the solution for those who expressed doubt in my approach.

var obj = {
    item_1: {name:'aaa',weight:4},
    item_2: {name:'ddd',weight:2},
    item_5: {name:'eee',weight:0},
    item_3: {name:'ccc',weight:3},
    item_6: {name:'ccc',weight:23},
    item_4: {name:'eee',weight:1},
}

var arr = _.toPairs(obj)

console.log(arr)

var sortedArr = arr.sort(function(a,b){ return b[1].weight - a[1].weight})

console.log(sortedArr)

var sortedObj = _.fromPairs(sortedArr)

console.log(JSON.stringify(sortedObj))

Explore and experiment with the code here: sort Object based on 'weight'property

Knowledge is key to understanding.

I have an array of objects that looks like this:

var obj = {
    item_1: {name:'aaa',weight:4},
    item_2: {name:'ddd',weight:2},
    item_3: {name:'ccc',weight:3},
    item_4: {name:'eee',weight:1},
}

When using methods like _.orderBy or _.sortBy()

For instance: _.orderBy(obj,['weight']) .

The resulting sorted array does not retain the original keys

0: {name: "eee", weight: 1}
1: {name: "ddd", weight: 2}
2: {name: "ccc", weight: 3}
3: {name: "aaa", weight: 4}

I require assistance in preserving the initial keys like item_1, item_2 etc. Can anyone help? Thank you.

Answer №1

Check out this helpful solution. Feel free to remove the additional property if necessary.

let data = {
    item_1: {name:'apple',weight:5},
    item_2: {name:'banana',weight:3},
    item_5: {name:'orange',weight:1},
    item_3: {name:'grapes',weight:4},
    item_6: {name:'watermelon',weight:10},
    item_4: {name:'strawberry',weight:2},
}

function createEntry(item, key) {
    let newEntry = { key: key };
    newEntry[key] = item;
    return newEntry;
}

function sortByWeight(entry) {
    return entry[entry.key].weight;
}

let itemsArray = _(data).map(createEntry).sortBy(sortByWeight).value();
console.log(itemsArray);

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 'v-model' directive necessitates a valid attribute value for the left-hand side (LHS)

I am facing an issue with my Vue application. I have a table where each row has its own unique id. I need to show or hide certain elements based on a condition in the v-model directive which compares the row id with a value in the model. The current code s ...

Determine the presence of an object within an array and apply an ng-class to it using AngularJS

Check out this Plunker for live demo: https://plnkr.co/edit/SRjkoo2mi5C2P1dVsYST?p=preview We have a total of 3 fruits: $scope.fruits = [{ _id: "3", name: "apple" }, { _id: "4", name: "orange" }, { _id: "5", name: "banana" }]; a ...

Transform the retrieved binary data into an object and then send it back

I have been working on a React function that fetches a .csv file stored in S3. The function reads the blob within the file, converts it to an object, and then returns it: import { Storage } from "aws-amplify"; import Papa from "papaparse&quo ...

Here's a guide on how to package and send values in ReactJs bundles

I'm currently involved in a ReactJs project that does not rely on any API for data management. For bundling the React APP, we are using Webpack in the project. The challenge now is to make the React APP usable on any website by simply including the ...

Setting the ajax mock calls count to zero in Jest test suites

In my current testing setup, I have a test structure that involves using ajax calls and mocking them based on the Jest tutorial found here: describe('it behavior', function() { it('is as it is', function() { jQuery.ajax.mock.call ...

My initial reaction to the code

I recently completed my first React code, which is the classic "Hello World" example. Unfortunately, I'm encountering some issues with it and despite trying various solutions, nothing seems to work. Below is the code snippet: <html> <h ...

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...

What causes certain images to have unspecified height and width measurements?

Currently, I am in the process of extracting image sizes from a website using a module called scraperjs. Most images have their height and width attributes defined, but some do not, resulting in the returned value being "undefined". How can I retrieve the ...

Warning from Vue: Steer clear of directly changing a prop as it will be replaced whenever the parent component undergoes re-rendering

I've been diving into Vue.js, but I'm encountering an issue. Every time I try to click on the "edit age" or "change my name" button, I get the following error message. [Vue warn]: Avoid mutating a prop directly because the value will be overwrit ...

Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the del ...

Creating a matrix filled with zeros and setting a specific element to one can be accomplished in LISP by utilizing

I am attempting to create a two-dimensional matrix filled with zeros, and then set certain items to one. This is the code I have tried: (defun my_array () (setq x (make-array '(5 5))) (setf (aref x 3 3) 1) (setf (aref x 3 4) 1) ...

Is there a more aesthetically pleasing method for verifying DBNull while constructing a string array?

Presently, I am utilizing the following approach: string[] AudienceTags = ((string[])(relResults["NEVCOAudienceTag"].GetType() == typeof(DBNull) ? null : relResults["NEVCOServiceTag"])); However, this code is quite lengthy. Is there a more efficient meth ...

The AJAX jQuery function encountered an empty error callback when the server operation was successful

When I make an ajax call using jQuery: $.ajax({ url: 'Login.aspx/AuthenticateRegularUser', type: 'POST', contentType: 'application/json; charset=utf-8', async: true, dataType: "json", data: '{ "em ...

Neglecting asynchronous Ajax functions once they have been called

I currently have a function that looks like this: $("#transfer").click(function(){ var token_rec = $("#token_rec").val(); var user_rec = $("#user_rec").val(); var subdomain_rec = $("#subdominio_rec").val(); var req_rec ...

Seeking out and upgrading essential information: how to do it effectively?

I am working with a document in a mongo collection that looks like this: { "_id" :"sdsfsfd323323323ssd", "data" : { "('State', 'Get-Alert', 'BLIST_1', 'MessageData')" : [ "$B_Add-Server", ...

How can a nested struct array be constructed?

I am working on creating an array of 1000 positions in my code. Each position contains a struct with an int (acting as a counter) and a nested struct initialized as an array of 100 positions. I need to confirm if this design is correct. My goal is to crea ...

Guide on utilizing the reduce method with objects

I am attempting to use the reduce method on an object to create an HTML list const dropdownTemplate = (data) => { console.log(data); // no data displayed return ` <li class="dropdown__item" data-value="${data.value}"><span class="dropdown__i ...

Understanding the behavior of invoking higher order functions can be quite perplexing

I'm encountering an issue with invoking a function within another function. I can't figure out why I am unable to invoke a function using the following logic: function func1(futurefunc){ futurefunc(); } function func2(){ return 3+3; } func ...

What is the best way to store data in Firebase as a JSON object?

I need your help with storing a JSON string in Firebase. I have to update my app weekly with data, so I decided to store the information in a JSON format. After using an online tool to stringify it, I got a long string that looks like this: " ...

Issues with data retrieval in Ng-table

When I implemented ng-table with an ajax call, the function onBuscarTable wasn't being called. Even after checking the debugger console, it still wasn't working: What am I doing wrong? Here's the JavaScript code snippet: $scope.onBuscarT ...