Arrange array of objects based on a specific key

I am currently working with an array of objects that looks like this:

[
  {
    '1485958472927784961': {
      name: 'bruno fiverr',
      points: 6,
      user_id: '1485958472927784961',
      tweets: [Array]
    },
    '1414575563323420679': {
      name: 'ju',
      points: 7,
      user_id: '1414575563323420679',
      tweets: [Array]
    }
  }
]

My goal is to sort this array based on the number of points each user has. I attempted to achieve this using the array.sort method along with a custom function:

var top10 = array.sort(function(a, b) { return a.points > b.points ? 1 : -1; }).slice(0, 10);

However, I keep getting the original array without any changes. Is it possible to accomplish what I'm trying to do?

Answer №1

If you have an array containing a single object and you need to sort the values by a specific property, follow these steps:

  1. Retrieve the first object in the array using array[0]
  2. Convert the object's values into an array using Object.values
  3. Sort the values in descending order using (a,b) => b.points - a.points
  4. Select the top 10 elements with .slice(0,10)

const array = [
  {
    '1485958472927784961': {
      name: 'bruno fiverr',
      points: 6,
      user_id: '1485958472927784961',
      tweets: [Array]
    },
    '1414575563323420679': {
      name: 'ju',
      points: 7,
      user_id: '1414575563323420679',
      tweets: [Array]
    }
  }
];

const top10 = Object.values(array[0]).sort((a,b) => b.points - a.points).slice(0,10);

console.log(top10);

Answer №2

The initial array structure is unnecessary in this case. It would be more efficient to switch to an object format with key-value pairs:

const data = {
  '1485958472927784961': {
    name: 'bruno fiverr',
    points: 6,
    user_id: '1485958472927784961',
    tweets: [],
  },
  '1414575563323420679': {
    name: 'ju',
    points: 7,
    user_id: '1414575563323420679',
    tweets: [],
  },
};

You can then easily extract all the values to form an array of objects, which can be sorted accordingly.

const data = {
  '1485958472927784961': {
    name: 'bruno fiverr',
    points: 6,
    user_id: '1485958472927784961',
    tweets: []
  },
  '1414575563323420679': {
    name: 'ju',
    points: 7,
    user_id: '1414575563323420679',
    tweets: []
  }
}

const sorted = Object.values(data).sort(function(a, b) {
  return a.points > b.points ? 1 : -1;
}).slice(0, 10);

console.log(sorted)

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

Issue in JavaScript on IE9: SCRIPT5022 error: DOM Exception - INVALID_CHARACTER_ERR (5)

I am encountering an error with the following line of code: var input2 = document.createElement('<input name=\'password\' type=\'password\' id=\'password\' onblur=\'checkCopy(th ...

Code snippet for adding a div element with an embedded image using JavaScript

I am attempting to create a function that generates three div elements, each containing an image, and then appends them to the body using a for loop. As a beginner in JavaScript, I am struggling with this task. Can anyone please provide guidance on what ...

Exploring Angular Firebase Database Queries

This is my TypeScript file import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; @Component({ selector: 'app-candidate- ...

Discover the position of a pair of elements within two arrays using numpy

Having two arrays numpy namely x and y Given that x = [0, 1, 1, 1, 3, 4, 5, 5, 5] and y = [0, 2, 3, 4, 2, 1, 3, 4, 5] The length of both arrays is identical and the pair of coordinates I am seeking absolutely exists within these arrays. How do I go abou ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

What is the best way to pass compile-time only global variables to my code?

I am looking for a way to easily check if my code is running in development mode, and based on that information, do things like passing the Redux DevTools Enhancer to the Redux store. I know I can use process.env.NODE_ENV for this purpose, but I find it ...

Managing POST request data in Express: A step-by-step guide

Currently, I am facing an issue with my alert button on the client side, which has an event listener that is supposed to send data to the server. Below is the code snippet for the client side: alertBtn.addEventListener("click", () => { axios ...

Is it necessary to establish a connection to my mongodb database directly within my jest test file, or is it permissible to invoke functions from separate classes that handle the database connection?

Currently in the process of testing my database functions using jest. My javascript file contains a variety of functions that connect to the database, retrieve data, and return an array. The issue I'm facing is when calling these functions from my jes ...

Guide to populating a dropdown list using React

The dropdown in my form should be populated with the value of testType, but it's not displaying. I have checked the data being sent and it is correct, so I'm unsure why it's not showing up in the dropdown menu. I only want this to populate w ...

What Could be Causing the Error: Invalid Hook Invocation?

I'm encountering an issue with reading undefined props. I attempted to destructure props, but I require the hook calls. Is there a way for me to destructure props within a function or another method to solve this problem? ProductBrowse.jsx is respons ...

Troubleshooting Intel Edison application update issues

After setting up the IoT XDK, I decided to try out the blink example. Excitedly, I saw that the LED on pin 13 was blinking just as expected! But when I attempted to change the interval from 1000ms to 100ms and 3000ms, there was no difference in the blinkin ...

Simple HTML files on a local server are having trouble loading images and JavaScript, yet the CSS is loading

Having worked in web design for quite some time, I recently began working on a basic Angular app that is meant to be very simple. For this project, I am only using the angular files and a single html file as the foundation. As I started setting up the bas ...

UITableView not populating with an array

In my FavoritesTableViewController, I have a mutable array called "citiesArray" that stores city names. When a city button is pressed, it triggers a method to add a city name to the array. [self.citiesArray addObject:@"New York"]; After adding "New York" ...

What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success. import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,ma ...

Manipulating Objects Using Controls with a Simple Drag and Click

Currently, I'm working on a scene that consists of two spheres and a point light positioned at (0,0,0). Using Controls, I've managed to make the spheres rotate around the point. However, I'm having trouble getting the spheres to move when I ...

I am perplexed by the fact that my script loops through 20x20 times instead of only 20 times. I cannot figure out the reason for this discrepancy no matter how hard

I'm attempting to exhibit a form that is populated with data retrieved from a JSON file when the document loads. The script goes through the array stored in the data (which contains 20 items) and generates a form for each iteration, filling it with th ...

Best method for removing CrosshairMove event listener in lightweight charts

As per the documentation, using unsubscribeCrosshairMove allows us to remove a handler that was previously added with subscribeCrosshairMove. Our objective is to use unsubscribe... to eliminate previous handlers before re-subscribing with subscribe... af ...

Reflect a two-dimensional array on a display board within a JFrame

I'm currently working on developing a board game that features an n by n grid, with random letters in each cell. These letters are chosen at random from an array of strings. The program also includes a 2D array of buttons to place the letters on the J ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

What is the process for triggering an exception?

I have a specific function that converts a two-dimensional array into CSV format. The key requirement is that the function only supports text and numbers, triggering an error message for any other input types. Currently, when I execute the function, it s ...