Is there a way to arrange elements in an array based on the second value in each nested array?

I need help organizing an object

{a: 1, b: 20, c: 3, d: 4, e: 1, f: 4}
into the following format
{a: 1, e: 1, c: 3, d: 4, f: 4, b:20}
(sorting the object numerically in ascending order) using a specific set of steps. Here are the steps I have outlined:

  1. Define a function named 'sort' that takes an object as an argument, and includes an empty array named 'arr' within it.

  2. Iterate through the object and push each key-value pair as an array into 'arr'.

  3. Sort the array numerically based on the object values.

  4. Create an empty object named 'newObj'.

  5. Iterate through the array and assign the key and value to 'newObj' accordingly.

  6. Return 'newObj'.

I have started writing the code but I am encountering issues, particularly with the sorting part.

function sort(object) {
    var arr = []
    var newObj = {}

    Object.entries(object).forEach(function(element, index) {
        arr.push(element)
    })

    arr[index][1].sort(function(a, b){return b-a});  

    arr.forEach(function([key, value], index) {
        newObj[key] = value
    })
    return newObj
}

What improvements can I make to this code to ensure the function works correctly?

Answer №1

To obtain a new object, you can sort the entries based on the second index.

var object = { a: 1, b: 20, c: 3, d: 4, e: 1, f: 4 },
    result = Object.fromEntries(
        Object
            .entries(object)
            .sort((a, b) => a[1] - b[1])
    );

console.log(result);

When using your algorithm,

arr[index][1].sort(function(a, b){return b-a});  

it is necessary to sort the entire array by

arr.sort(function (a, b) { return a[0] - b[0]; });

Array#sort utilizes a callback function with two parameters representing each item, returning the desired order between the elements.

In this scenario, each array of entries serves as parameters, such as

['a', 1]
['b', 20]

From these arrays, extract the value at index 1 and calculate the difference to determine the sorting order.

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

Navigating Redirect Uri in Ionic for third-party API integration

After creating a webapp, I decided to venture into developing a mobile app using Ionic. The idea of making a progressive web app crossed my mind, but unfortunately Apple doesn't support it yet. (By the way, I'm still quite new to all of this) F ...

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...

In the world of programming, there exists a mysterious creature known as

I've been experimenting with different methods, but nothing seems to be working for me. What I am attempting to accomplish is <?php $php_var = a-thing; echo ' <script text/JavaScript> document.cookie = "arrayid"+&apos ...

Using AngularJS to iterate through a nested array with ng-repeat

Hey everyone, I've been working on a project where I have an array called menu[] with nested arrays called flavors[] within it. My goal is to calculate the total price of all active items and flavors in the menu. While I was able to successfully calcu ...

Ensure that the input remains below ten

My goal here is to ensure that the value in an input element is a non-zero digit (0<x<=9). Here's the HTML tag I'm using: <input type="number" class="cell"> I've experimented with various JavaScript solutions, but so far none h ...

Messages using JQuery input technology

My form includes two inputs. The first input must be completed before moving on to the second. If the user selects the second input before the first, they will receive a message instructing them to fill out the initial input. I now want to ensure that aft ...

Troubleshoot: Bootbox Confirm Functionality Issues

Can anyone help me troubleshoot this issue? I'm trying to implement code that uses bootbox.confirm when deleting a file, but it's not functioning correctly. $('#fileupload').fileupload({ destroy: function (e, data) { var that = $(th ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

Interacting with API through AngularJS $http.get

I am a beginner in AngularJS and I am trying to grasp its concepts by studying example codes. Currently, I have found an interesting code snippet that involves the $http.get function. You can find it here: I attempted to replace the URL with my own, but ...

What is causing this code to malfunction?

Currently delving into the world of Ajax, I've been following a tutorial and have crafted the script below: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function MyFunction(){ var xmlhttp; if(windo ...

E6 arrow functions simplify the process of condensing an array of objects into a single object

Here is an array that I have: a=[{'test':1,'test2':'2'},{'test':3,'test2':'4'}] My goal is to reduce this array into a single object This is the expected output {1:2,3:4} I attempted the foll ...

Navigating a JSON array using the Handlebars template engine

I have a JSON file and I am looking for guidance on how to display the information from it using the handlebars template engine: This is the template code: <script id="template-app" type="text/x-handlebars-template"> {{#each data}} Emai ...

Executing the collection.find() function triggers an internal server issue and eventually leads to a timeout error

My ExpressJS backend was running smoothly with hardcoded data, but when I integrated MongoDB into the system, my requests for data started timing out. I added a record to a collection using the command prompt: > db stackmailer > db.sites.find() { ...

Implementing Autocomplete search with jQuery Chosen plugin - a step-by-step guide

CSS <select class="custom" id="company_hub" name="company_hub" style="width: 400px; display: none;"> <option>-Select Item-</option> </select> https://i.sstatic.net/x4YtN.png I attempted the following method but it was unsucces ...

Customize Your AJAX POST URL with Radio Buttons - A Step-by-Step Guide

I'm looking for some guidance on how to use AJAX to change the post URL based on a radio button selection. Do I need to use an if statement or is there another way? var barray = []; function cbutton() { $('input:radio[name="cheking"]:checke ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...

Is there a way to modify the color of the horizontal line within react-native-otp-inputs in the React Native platform?

Is there a way to customize the color of the horizontal line in react-native-otp-inputs for react native? I used react-native-otp-inputs to capture user OTP input, but now I want to change the color of the default black horizontal line to white. You can re ...

Generate Swagger documentation for an API developed using Express 4.x

My challenge lies in documenting my Node and Express 4 server with Swagger for a client. I have explored various tools for this purpose, but haven't found the perfect fit yet. The swagger-node-express tool seems promising, but unfortunately does not ...

Troubleshooting issue: EJS loop not functioning correctly when handling JSON information

Having an issue with looping in an EJS file. Here's the data I'm working with: { "name": "Marina Silva", "info": [{ "periodBegins": "Sun Apr 14 23:48:36 +0000 2011", "periodFinishes": "Sun Apr 7 23:48:36 +0000 201 ...

There was an issue with locating the module: Error: Unable to find the specified module 'vue-axios' in the directory 'C:xampphtdocsvue-laravel-api esourcesjs'

I am currently working on a CRUD project using Laravel and Vue.js. I made sure to install all the necessary devDependencies, but when I try running NPM run watch, I encounter the following error: https://i.sstatic.net/Kqkpq.png My app.js file includes all ...