I have been given an array of objects. I need to figure out how to filter this array so that only the groups with the highest values are retained, ensuring that each group

[
{"marks": 99, "set":"A"},
{"marks": 90, "set":"B"},
{"marks":"10", "set":"A"},
{"marks":"10",      "set":"B"},
]
 

Working with TypeOrm at the moment and looking to apply filtering on data.

Expected outcome array:

[
{"marks": 99,      "set":"A"},
{"marks": 90,     "set":"B"},
]

Answer №1

const dataset = [
{"rating": 99, "category":"A"},
{"rating": 90, "category":"B"},
{"rating": 10, "category":"A"},
{"rating": 10, "category":"B"}]

const outcome = [...new Set(dataset.map(i=>i.category))] // obtain distinct category ids
  .map(c=>dataset.filter(({category})=>c===category) // explore members of each group 
  .sort(({rating:a},{rating:b})=>a-b).pop()) // find the one with highest rating

console.log(outcome)

If your data includes ratings that are strings rather than numbers, modify a-b to (+a)-(+b) to coerce the strings into numbers.

Answer №2

In situations like this, my go-to choice would be utilizing the powerful capabilities of Lodash library.

function findMaxScoreGroups() {
let data = [
    {"score": 99, "group":"1"},
    {"score": 90, "group":"2"},
    {"score": 10, "group":"1"},
    {"score": 10, "group":"2"},
]

let groupedData = _.groupBy(data, "group")
let maxScoresByGroup = _.map(groupedData, group => (_.maxBy(group, 'score')));
console.dir(maxScoresByGroup)

}

Answer №3

If you want a more efficient solution, consider using a single loop along with an object to store the group information.

const
    info = [{ score: 99, group: "1" }, { score: 90, group: "2" }, { score: 10, group: "1" }],
    highestScore = Object.values(info.reduce((result, obj) => {
        if (!result[obj.group] || result[obj.group].score < obj.score) result[obj.group] = obj;
        return result;
    }, {}));
    
console.log(highestScore);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

To achieve this, aggregate the collection based on the group attribute while retaining only the objects with the highest score. The approach involves utilizing a Map for accumulation and then spreading the iterator generated by Map.values() to obtain the desired outcome.

const data = [{ score: 99, group: '1' }, { score: 90, group: '2' }, { score: '10', group: '1' }, { score: '10', group: '2' },];

const aggregated = data.reduce(
  (accumulator, obj) =>
    !accumulator.has(obj.group) || obj.score > accumulator.get(obj.group)?.score
      ? accumulator.set(obj.group, { ...obj })
      : accumulator,
  new Map()
);

const finalResult = [...aggregated.values()];

console.log(finalResult);

Answer №5

Just for kicks, here's an alternative version:

let numbers = [2, 4, 6, 8, 10];
let sum = numbers.reduce((acc, curr) => acc + curr, 0);

console.log(sum)

This method is not only simple and easy to understand but also efficient in terms of performance.

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

Receiving messages in AngularJS with the help of Strophe.js

My XMPP client in AngularJS, inspired by this stackoverflow link. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d282e382f1d282e382f7331323e3c31">[email protected]</a> can send messages successfully, but <a hr ...

Searching for and modifying a specific subdocument in Mongoose

I am currently working with the schema for a document called Folder: var permissionSchema = new Schema({ role: { type: String }, create_folders: { type: Boolean }, create_contents: { type: Boolean } }); var folderSchema = new Schema({ nam ...

Set JSON Value Session

In the table, there is an option to edit certain entries using a button. I have developed a function that retrieves JSON data and populates the table with it. This process happens before any other actions. Once the data is loaded, my goal is to create a c ...

Tips for overlaying text on the background in Next.js:

I'm currently working on creating an image element with overlay text. Check out my jsx code below: <div className={styles.img}> <img src={src} alt="" /> <p>{`(${size})`}</p> </div> And here is t ...

Creating a dropdown menu using Vue.js

My latest project involves coding an html page that features a drop-down list using HTML, CSS, and VueJS. The goal is to have something displayed in the console when a specific option from the drop-down list is selected. Here's the snippet of my html ...

I am able to upload an image using ImagePicker.openPicker in my React Native app, however, I am encountering difficulties

Currently, I am in the process of developing an application using react native. Within the app, users have a profile image that can be updated by either selecting one from the gallery or capturing a new one with the camera. The library utilized for this ...

Facing an issue where the CSS class name is not displaying correctly when utilizing CSS Modules with my React

This webpack.config.js file is dedicated to the module section, where loaders are defined for JSX files and CSS. module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'bab ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Anchor no longer follows endpoint after Anchor ID is modified following creation - JSPlumb

I am currently developing an editor that involves placing shapes on a canvas and assigning IDs to them. When a shape is placed, endpoints are automatically created and attached to the shape using its ID as an anchor. //Function responsible for adding en ...

Grant permission for a user to attach a collection to their specific user identification number

I am encountering difficulties while attempting to execute a POST request to an endpoint in order to update a user's profile with a collection associated with their USERID. The issue I keep running into is a 401 unauthorized error. THE ROUTER: router ...

Exploring the concept of rest arrays within a destructured object

Is there a way to declare c as an optional array of any type in this code snippet? const a = ({ b, ...c }: { b: string, c: ? }) => null ...

Can you provide the Angular JS alternative for executing a POST request similar to this Curl command?

Trying to translate a Curl command into Angular JS code has been a challenge for me as a newcomer to AngularJS. This specific instance involves a mobile app built on the ionic framework, which utilizes Angular JS. The original curl command looks like this ...

A function that retrieves an array containing elements that exceed a specified number and a given array

Is there a way to create a function that takes an array and a number as parameters, then returns a new array with only the elements from the original array that are greater than the given number? For example: [10, 25, 16, -5, 30, 15, 24] , 16 The output ...

The background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

Issues with dynamically generating buttons using Ajax and Javascript technology

In order to dynamically create buttons based on the contents of a text file during the onload event, I have written a JavaScript function. However, despite being able to read the file and using alert messages to verify the correctness of the variable &apos ...

TypeScript: The class results in an empty object being returned

I'm encountering an issue with a Typescript Class that I'm attempting to use. Even after instantiating it, I'm not getting the correct class instance. Class GamesService export interface IGame { name: string; online: number; likes: n ...

Update the text box with the value of the checkbox selected before

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <link rel="stylesheet" href="ios7-switches.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <styl ...

jQuery enables the creation of fresh form fields

Currently, I am working on a form that initially consists of 2 text input fields. The typical use case involves the user entering a number in one field and their name in the other. Following this, the page updates itself without reloading. However, there a ...

The value specified as type '{ value: BigNumber; }' cannot be assigned to the parameter type 'Overrides & { from?: string | Promise<string> | undefined; }'

I am currently working on a smart contract using Solidity (version 0.8.0) at my buildspace project. Below is a snippet of my code written in TypeScript (4.5.x)/JavaScript and Node.js 16.13.x: ... const waveContractFactory = await hre.ethers.getContractFact ...

Send information from a POST route to a template

I am currently working on developing a basic weather application using node.js. My goal is to present weather details in a separate ejs file. Here's a snippet of my code within the post route: app.post('/', (req, res) => { var locat ...