Tips for obtaining the top 3 highest-value objects in a JavaScript array over all other elements

I am working with an array that contains objects, each with two properties: name and value.

array = [
 {
  name: 'name1',
  value: 0
 },
 {
  name: 'name2',
  value: 2
 },
 {
  name: 'name3',
  value: 4
 },
 {
  name: 'name4',
  value: 4
 },
 {
  name: 'name5',
  value: 3
 },
 {
  name: 'name6',
  value: 2
 },
 {
  name: 'name7',
  value: 0
 },
 {
  name: 'name8',
  value: 1
 },
 ...
]

I am trying to retrieve the objects with the highest value property from this array. Specifically, I want to get the objects with value = 4, value = 3, and value = 2 (the top 3 values).

let firstValue = 0;
let secondValue = 0;
let thirdValue = 0;
array.map((obj) => {
    if (obj.value > firstValue) {
        thirdValue = secondValue;
        secondValue = firstValue;
        firstValue = obj.value;
    } else if (obj.value > secondValue) {
        thirdValue = secondValue;
        secondValue = obj.value;
    } else if (obj.value > thirdValue) {
        thirdValue = obj.value;
    }
})

The issue I'm facing is that when there are multiple objects with the same value, my current method only returns one of them instead of all.

Answer №1

In order to retrieve the top 3 values from an array, it is necessary to first sort the array and then filter out the elements with the top 3 values. To achieve this, a separate array can be used to keep track of whether all elements with the same value have been pushed or not.

var pickedValues = [];
array = array
  .sort((a, b) => a.value > b.value ? -1 : 1)
  .filter(el => {
    if(pickedValues.length === 3 && !pickedValues.includes(el.value)) return false;

    if(!pickedValues.includes(el.value)) pickedValues.push(el.value);

    return true;
  });

Below is the code snippet demonstrating the functionality:

var array = [{
    name: 'name1',
    value: 0
  },
  {
    name: 'name2',
    value: 2
  },
  {
    name: 'name3',
    value: 4
  },
  {
    name: 'name4',
    value: 4
  },
  {
    name: 'name5',
    value: 3
  },
  {
    name: 'name6',
    value: 2
  },
  {
    name: 'name7',
    value: 0
  },
  {
    name: 'name8',
    value: 1
  },
];

var pickedValues = [];
array = array
  .sort((a, b) => a.value > b.value ? -1 : 1)
  .filter(el => {
    if(pickedValues.length === 3 && !pickedValues.includes(el.value)) return false;
    
    if(!pickedValues.includes(el.value)) pickedValues.push(el.value);
    
    return true;
  });
  
console.log(array)

Answer №2

Step-by-step guide on how to accomplish this:

const elements = [
 {
  name: 'element1',
  value: 0
 },
 {
  name: 'element2',
  value: 2
 },
 {
  name: 'element3',
  value: 4
 },
 {
  name: 'element4',
  value: 4
 },
 {
  name: 'element5',
  value: 3
 },
 {
  name: 'element6',
  value: 2
 },
 {
  name: 'element7',
  value: 0
 },
 {
  name: 'element8',
  value: 1
 }];

let sortedElements = elements.sort(function(a, b) {
    if (a.value > b.value) { return -1 };
    if (a.value < b.value) { return 1 };

    return 0;
});

console.table(elements.splice(0, 3));

Answer №3

To begin, it is important to organize the array by utilizing the default sort method. It is advisable to make a copy using the spread syntax in order to avoid altering the original array.

After sorting, you can utilize the slice method to extract the necessary elements.

Take a look at the following code snippet:

let array = [
 {
  name: 'name1',
  value: 0
 },
 {
  name: 'name2',
  value: 2
 },
 {
  name: 'name3',
  value: 4
 },
 {
  name: 'name4',
  value: 4
 },
 {
  name: 'name5',
  value: 3
 },
 {
  name: 'name6',
  value: 2
 },
 {
  name: 'name7',
  value: 0
 },
 {
  name: 'name8',
  value: 1
 }
]

let sortedArray = [...array].sort((a,b) => b.value - a.value)

// Now that the array is sorted in descending order, you can select the first three or any desired amount

console.log(sortedArray.slice(0,3))

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

Dropbox menu within an extended webpage

I am looking to create a dropdown menu that behaves like the one on this website. The goal is for the dropdown to cover the entire webpage, hide the scroll bar, and "unmount" the other elements of the page, while still displaying them during the transition ...

How can I use HTML to display a new image next to the base image when I hover over it, showing both images side by side?

Looking for assistance with creating a comic webpage containing 2 cartoons. I want the dialog or mind-thought of each cartoon to appear on the page when a user hovers over them. Anyone able to offer some help with this? ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...

What is the best way to loop through arrays of objects within other arrays and delete specific attributes?

I have an array of JavaScript objects with potential children who share the same type as their parent. These children can also have their own set of children. My goal is to loop through all nodes and modify certain values. [ { "text": "Auto", ...

How to effectively utilize signed requests for AWS S3 when uploading images?

My project involves developing a react native application similar to Slack, and I'm currently facing an issue with image uploads to S3. I decided to use the getSignedUrl route for this functionality. The process goes as follows: the client selects a ...

Tips for updating one-time binding data in AngularJS

I am currently facing an issue with a div that displays details such as mobile number, name etc. in the format: {{::mobilenumber}}, {{::name}} Within this div, there is a button that when clicked should populate the same values in a new form However, des ...

Enhancing particular components within C array

I'm struggling to visualize the process for handling some of my code. Within my C program, I need to compare each element of an array of structs (referred to as arr_person[i].name) to a user's input in order to check for matches. For example, if ...

Webpack in Vuejs does not have access to the keys defined in dev.env.js file

The framework utilized here is vuejs-webpack, with build and config files located here. No modifications have been made to these files. According to the information on Environment Variables, the keys specified in dev.env.js should be accessible during the ...

Strategies for effectively handling errors in the requestAnimationFrame function

I'm currently facing issues with the animate() function, as it tends to crash my browser and cause my computer to heat up when errors occur. I attempted to use a try/catch handler to handle these errors but it did not work as expected. animate(){ ...

JavaScript string: Use regex to find and replace with position index

I'm not very familiar with regex, so I'm curious about the process of replacing a section in a string based on a regex pattern where the index is part of the identified section. Let's consider this example string: let exampleStr = "How do ...

Tips for sending information to an Express API through AJAX

While working on a website using Express and EJS, I encountered an issue with calling an API via AJAX. The problem arises when passing two values to the AJAX data upon button click, resulting in errors. Despite trying various solutions, I'm still stru ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

When exporting a Mongoose model, it mysteriously becomes undefined

I am encountering an issue when trying to import the DemandeTransports model from a specific file: //@/components/database/model/Schema.js import { Schema } from "mongoose"; import mongoose from "mongoose"; const userSchema = new Schem ...

AngularJS - displaying a notification when the array length is empty and customizing the visibility to conceal the default action

I've been working on an Angular project where I display a loading circle that disappears once the content is loaded. This circle is simply a CSS class that I call from my HTML only when the page first loads, like this: Actually, the circle consists o ...

Exploring the power of combining observables in RxJS

Having difficulty combining observables in my implementation of a tags-input feature. this._allTags represent all available tags. I am working with 4 streams: this._suggestions = new this.rx.Subject; this._searchText = new this.rx.Subject; this._s ...

Guide on setting up a configuration node in Node-RED

I am attempting to create a config node similar to this example, but it only displays a text box and not the configuration options. I want the projectid to be a config node, and despite trying various nodes with config setups, nothing seems to work for me. ...

When a user clicks on a child element in ReactJS, the onclick event returns as undefined

I am experiencing an issue with my restaurants list component. While I have an onClick event set up for each list item, clicking on a child element of the list item does not trigger the expected response. When this occurs, nothing happens or I see an undef ...

What is the best way to alter something based on the current date?

My goal is to dynamically change a message based on how close a specific date is. The objective is to update an element of a webpage to display "Renewal Unnecessary" when the date is more than 3 months away, "Renewal upcoming" when the date is less than 3 ...

React Redux in conjunction with redux persist ensures that only a portion of the data remains stored persistently

This app is built using React Native with the Redux pattern and redux-persist to store data for offline use. However, only some of the data is persisting correctly. For example, the `auth` data is persisting and loading from `AsyncStorage` without any issu ...

The assignment of type 'string' to type 'UploadFileStatus | undefined' is not permissible

import React, { useState } from 'react'; import { Upload } from 'antd'; import ImgCrop from 'antd-img-crop'; interface uploadProps{ fileList:string; } const ImageUploader:React.FC <uploadProps> ...