How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields.

I understand how to select the value itself:

Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; }))

... but I am unsure of how to achieve the same result and return the entire object instead of just the value.

Answer №1

If you want to find the object in an array with the highest value for the property DisplayAQI, you can achieve this using the reduce method.

let list = [ {DisplayAQI : 20}, {DisplayAQI : 100}, {DisplayAQI : 200}, {DisplayAQI : 10} ];

let result = list.reduce((c, v) => c.DisplayAQI > v.DisplayAQI ? c : v);

console.log(result);

Resource: Learn more about reduce() on MDN

Answer №2

myArrayOfObjects.sort((object1, object2) => {
    return object1.property - object2.property
})[0]

Just sort your array based on a specific property and fetch the first element from the sorted list.

Answer №3

One alternative method is to organize the array of objects in descending order and then retrieve the element from the 0th index

let values = [{
  DisplayAQI: 20
}, {
  DisplayAQI: 100
}, {
  DisplayAQI: 200
}, {
  DisplayAQI: 10
}];

let output = values.sort(function(a, b) {
  return b.DisplayAQI - a.DisplayAQI

})[0];
console.log(output)

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

Retrieve the final variable in an Observable sequence

In my code, I have a variable called 'messages' which stores messages from a conversation: messages: Observable<Message[]>; To populate the 'messages' variable, I do the following: const newMessage = new Message(objMessage); ne ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

Guide to utilizing @types/node in a Node.js application

Currently, I am using VSCode on Ubuntu 16.04 for my project. The node project was set up with the following commands: npm init tsc --init Within this project, a new file named index.ts has been created. The intention is to utilize fs and readline to read ...

Troubleshooting Angular JS loading problems

I'm attempting to implement the Angular-Spinner in my project: Specifically, I want to use it with http.get calls. This is what I have so far: Within controllers: $scope.loading = true; $http.get('js/data/test.json').success(function(resu ...

Using JavaScript variables within an @if statement in Laravel within the innerHTML segment

How can I incorporate a JavaScript variable 'x' into an @if statement in Laravel? I have tried placing it both inside and outside of the @if statement. When placed outside, it works perfectly fine, but I really need to perform an action based on ...

Creating a Dojo HTML template involves incorporating repetitive sections of HTML code within the template structure

I am working with a custom Dojo widget that is based on a template and has an HTML template stored in a separate .html file. Here is the Dojo Widget code snippet: define("dojow/SomeWidgetName",[ "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_Templat ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

Issue encountered when populating FormArray with a FormGroup inside a loop in Angular version 17

Encountering an error while trying to populate a FormArray in Angular (version 17): Issue arises at line 44 with the error message: Argument of type 'FormGroup<{ name: FormControl<string | null>; amount: FormControl<number | null>; }&g ...

Display a complete inventory of installed typings using the tsd command

How can I display a list of all installed tsd typings in the terminal? Perhaps using the following command: $ tsd list ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

Adding an object to an array in Postgres with TypeORM

I am currently facing an issue with the column in my Postgres database that has a data type of json. The code snippet for this scenario is as follows: @Column({ type: 'jsonb', nullable: false, default: [] }) us ...

Is it possible to adjust the width of a parent element based on the number of child

In this particular example, I have structured a header with a logo-container positioned on the left side, a menu in the center, and a button on the right. The menu consists of 5 top-level items and 2 sub-menus. <div class="container"> <div cla ...

Unraveling the Mystery of jQuery Syntax

Upon reviewing jquery.ui-1.8.11.js: $.extend(Datepicker.prototype, { /* A unique class name appended to elements indicating they are configured with a date picker. */ markerClassName: 'hasDatepicker', /* For debugging purposes (if e ...

You must include the formControlName within a parent formGroup directive

Upon creating a model-driven form, an error is encountered: Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). ...

Unable to see or play local mp4 file in Ionic iOS application

I am facing an issue with my Ionic app where I am trying to show a video playing in the background. The Jaeger25 HTMLVideo plugin works perfectly for Android, but when it comes to iOS, the video simply refuses to play. The video file is located in the www/ ...

Incorporating HTML with ng-binds through transclusion

I have been developing an angular directive to enhance the functionality of ng-table by adding filtering and exporting features. The main goal is to make this directive reusable for multiple tables, which requires the <td> elements to be dynamic. To ...

What could be causing me to have to click the button twice in order to view my dropdown list? Any suggestions on how to

I am facing an issue where I have to click twice on the "Action" button in order to see my dropdown list. How can I resolve this? Is there a way to fix it? $(document).ready(function() { $(".actionButton").click(function() { $dropdown = $("#cont ...

Importing modules using relative paths results in failure due to module not being found, whereas employing absolute paths

I have been encountering this problem for a considerable amount of time and have made multiple attempts to resolve it. I am currently working on the development of my discord.js bot and recently switched from TS back to JS due to certain complications I fa ...

Adding a class to the following DIV and smoothly transitioning the current one out can be achieved using a dynamic number of items in multiple instances

Is there a way to create a scalable CSS slideshow for text divs without using images? Here is the current HTML structure: <div class="mb-panel-container cf"> <div class="mb-panel-section mb-slider"> <div class="mb-panel active" ...

Exploring the Functionality of Cookies in Nuxt 3 API Endpoints and Middlewares

Can cookies be utilized on the server side in Nuxt 3? For instance, I need to set a cookie in an API and then access its data in middleware: // ~/server/api/testApi.ts export default defineEventHandler(event => { /* setCookie('myCookie', ...