Discovering the highest value within an array of objects

I have a collection of peaks in the following format:

peaks = 
0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001}
1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333}

and so on.

I am looking to determine the peak with the highest value. I attempted to achieve this using the following code:

this.loadPeak = peaks.map(a => Math.max(a.value));

However, instead of getting the maximum value along with the intervalId and time, I only received an array of values from all peaks without obtaining the maximum value itself.

**I appreciate all the solutions provided. Although I cannot accept them all, they were all helpful. Thank you!**

Answer №1

Sorting an array can lead to unnecessary iterations, especially as the size of the array increases. This slows down the process significantly as elements are constantly moved around. By utilizing the reduce() method, we can efficiently handle this task by simply replacing the previous value with the current element if it is greater:

var peaks = [
  {intervalId: 7, time: 1520290800000, value: 54.95125000000001},
  {intervalId: 7, time: 1520377200000, value: 49.01083333333333}
];

const maxPeak = peaks.reduce((p, c) => p.value > c.value ? p : c);

console.log(maxPeak);

Answer №2

If you want to focus solely on the value aspect of Math.max, you can do so.

var peaks = [{ intervalId: 7, time: 1520290800000, value: 54.95125000000001 }, { intervalId: 7, time: 1520377200000, value: 49.01083333333333 }]
    max = Math.max(...peaks.map(({ value }) => value)),
    object = peaks.find(({ value }) => value === max);

console.log(max);
console.log(object);

Answer №3

The straightforward approach involves using a loop:

this.highestPeak = null;
for (const peak of peaks) {
    if (!this.highestPeak || peak.value > this.highestPeak.value) {
        this.highestPeak = peak;
    }
}

Example in Action:

const peaks = [
  {intervalId: 7, time: 1520290800000, value: 54.95125000000001},
  {intervalId: 7, time: 1520377200000, value: 49.01083333333333}
];

let highestPeak = null;
for (const peak of peaks) {
    if (!highestPeak || peak.value > highestPeak.value) {
        highestPeak = peak;
    }
}
console.log(highestPeak);

Just like with any array operation, you can also use the reduce method:

this.highestPeak = peaks.reduce((maxPeak, peak) => !maxPeak || maxPeak.value < peak.value ? peak : maxPeak, null);

const peaks = [
  {intervalId: 7, time: 1520290800000, value: 54.95125000000001},
  {intervalId: 7, time: 1520377200000, value: 49.01083333333333}
];

const highestPeak = peaks.reduce((maxPeak, peak) => !maxPeak || maxPeak.value < peak.value ? peak : maxPeak, null);
console.log(highestPeak);


I discovered that this was a duplicate question. I have identified the duplicate and tagged it accordingly. This is now a community wiki answer.

Answer №4

To find the highest value in your list of peaks, you can arrange them in descending order and select the first element.

let peaks = [{
    intervalId: 7,
    time: 1520290800000,
    value: 54.95125000000001
  },
  {
    intervalId: 7,
    time: 1520377200000,
    value: 49.01083333333333
  }
]

let sortedPeaks = peaks.sort((a, b) => b.value - a.value)

let highestPeak = sortedPeaks[0];

console.log(highestPeak);

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

MUI DataGrid Identifying Duplicate Rows

I'm encountering an issue with my Data Grid component from MUI when fetching data using axios. The console shows the correct data, but on the page, it only displays one result or duplicates. I suspect there might be a frontend problem, but I'm s ...

"Securing Your Web Application with Customized HTTP Headers

I'm currently working on setting up a POST request to a REST API (Cloudsight) with basic authorization. Here is the code I have so far: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://api.cloudsightapi.com/image_requests", true); xhr.setRequ ...

What is the best way to have my sliding panel automatically close when I click outside of it?

I have created a sleek sliding navigation panel for my website that appears when the screen width is reduced. Although I am satisfied with how it functions currently, I would like the panel to close when the user clicks/taps outside of it. What adjustments ...

The issue with Infinite Scrolling/Pagination feature in backbone.js persists

My goal is to implement an infinite scroll feature similar to Twitter using the Pagination plugin for backbone.js. Clicking the button/link #pagination a should load the next page of results from the backend and append it to the current view PhotoListView. ...

Having trouble accessing the property 'keys' of undefined in React event handling operations

I am currently working on implementing a button that executes Javascript code roshtimer(), along with the ability for users to trigger the command using hotkeys. Users should have the option to either click the button or press 'r' on their keyboa ...

Error: The function list.forEach does not exist within service.buildList [as project]

Today, I've been grappling with a challenging issue. As someone new to Typescript and Angular, I'm attempting to make a call to my backend API. However, when trying to populate an array for display, I keep encountering an error that says rawRegis ...

Utilizing Cell References in the Table Component of React Material UI

I'm exploring React and aiming to create an editable table that dynamically updates the $/Unit cell based on changes in the Price and Units cells. I'm having trouble figuring out how to access values from other cells. Can this be achieved using ...

Angular binding for selecting all data

Upon checking a checkbox for a single item, the bound data is retrieved and added to an array. However, this does not happen when using selectAll. Code snippet in Angular for obtaining the object of a checked item: $scope.selectedOrganisations = []; $sco ...

How to Hide Warning Messages in Angular NPM Package for Production Environment

Seeking advice on a coding issue I'm facing. Currently, I am in the process of creating an npm package for angular / angular material, which involves implementing some checks. If a developer fails to pass a specific argument to my function, the funct ...

Obtaining connection data in jsPlumb can be accomplished through a variety of

I have created a compact table of nodes that allow me to drag and drop connections or manually input node IDs to establish connections between them. Despite searching through the documentation and scouring the internet for examples, I am struggling to fin ...

Setting up a service in angularjs that is reliant on another service

One thing I'm trying to figure out is how to utilize a service like $http outside of the $get function. Is this even possible? Currently, my code loads a json file that contains a dictionary used by my application in various ways. I want users to have ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format. Cu ...

Is there a way to seamlessly transition between different Angular components without having to refresh the entire webpage?

I'm currently working on implementing a navigation bar that allows users to switch between three components without having the navbar reload. The goal is for only the new component to load when the user clicks on a different section of the navbar, kee ...

What is the best way to utilize a single Google Map component instance across multiple children?

Seeking a method to maintain the same Google Map instance throughout my entire app, as each map load incurs charges... Currently utilizing google-map-react. An instance of a new Map is created in ComponentDidMount, suggesting that it's important to k ...

Multi-Slide AngularJS Carousel

My current setup includes a carousel like so: <div> <carousel id="myC" interval="3000" > <slide ng-repeat="order in orders"> <img ng-src="whatever.jpg" style="margin:auto;"> <div ...

Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreci ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

Hold off until all commitments are fulfilled in Firestore

Is there a way to ensure that all promises are resolved before moving on to the next line of code? Currently, it seems like it's moving to the next line without completing the operation below. I want to make sure that the forEach loop is fully execute ...