How to retrieve the object's property with the highest numerical value using JavaScript

My current object is structured as follows:

const obj = {
    happy: 0.6,
    neutral: 0.1,
    said: 0.3
}

I'm trying to determine the best method to retrieve the property with the highest value (in this case, it would be "happy"). Any suggestions on how I can achieve this?

Answer №1

To retrieve the key-value pairs, you can utilize Object#entries. To find the property with the greatest value, you can make use of Array#reduce:

const obj = { happy: 0.6, neutral: 0.1, said: 0.3 };

const propWithLargestValue = Object.entries(obj).reduce((prop, [key,val]) =>
  val > (obj[prop] || Number.MIN_VALUE) ? key : prop
, null);

console.log(propWithLargestValue);

Answer №2

If you want to accomplish this task effortlessly, just utilize the power of Object.entries

const obj = {
  happy: 0.6,
  neutral: 0.1,
  sad: 0.3,
};

const result = Object.entries(obj).sort((a, b) => b[1] - a[1])?.[0]?.[0];
console.log(result);

Answer №3

If you want to determine the maximum value among the entries of the object and then find the first entry with that value, you can use the following code:

const maxValue = obj => (entries =>
  (max => entries.find(([k, v]) => v === max))
  (Math.max(...entries.map(([key, val]) => val))))
(Object.entries(obj));

const obj = {
  happy: 0.6,
  neutral: 0.1,
  said: 0.3
};

const [ key, value ] = maxValue(obj);

console.log(key);   // happy
console.log(value); // 0.6

Code golf

You can shorten the above function to only 86 bytes:

f=o=>(e=>(m=>e.find(([,x])=>x===m))(Math.max(...e.map(([,v])=>v))))(Object.entries(o))

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

Which function is triggered first - onclick or ng-click?

Currently, I have a button with a validation process occurring on click. The validation process triggers a web service call and other processes if successful. However, I'm uncertain if the validation is actually taking place. This is my page setup: ...

The jQuery click event does not fire within a bootstrap carousel

I am trying to set up a bootstrap carousel where clicking on an image inside it will trigger a self-made lightbox. However, I am facing some issues with the JavaScript code not being triggered with the following syntax: $('html').on("click", ".l ...

Executing various count() queries on a MongoDB using mongoose

Hey there, I consider myself a MongoNoob and I know this question has probably been asked before in various ways, but I haven't found a specific solution yet. Let's imagine I have two Moongoose Models set up like this: var pollSchema = mongoose. ...

The error message "TypeError: Cannot set property 'href' of undefined" occurred at angular.js line 12520 when trying to set $window.location.href

Has anyone tried using a directive function to redirect when clicking with ng-click? Here is the HTML code: <a ng-click="navbarlinksCtrl.clickedfr()" ng-class="{active: clickedfr()}">FR</a><br> <a ng-click="navbarlinksCtrl.clickeden( ...

Only display entries with no content

When attempting to filter data from a search, all results are being displayed on the submit button even when entering 1, 2, or 3. Here is my code below. Please let me know if I am making a mistake somewhere. ...

Struggle with implementing enums correctly in ngSwitch

Within my application, I have implemented three buttons that each display a different list. To control which list is presented using Angular's ngSwitch, I decided to incorporate enums. However, I encountered an error in the process. The TypeScript co ...

Determine the dropdown list value by analyzing the final two variables in a textfield

In my textfield, car registration numbers are meant to be entered. These registrations are based on years in the format GT 74454 12, with the last two digits "12" representing the year 2012. I am looking for a script that can automatically detect the last ...

Ways to Loop Through a Set of Information and Retrieve it as a List

Here is some sample data: 0: {rowid: "4b531532a5a9", groups: "Group1", descriptions: "Item1"......} 1: {rowid: "e55315ccabb5", groups: "Group2", descriptions: "Item2"......} 2: {rowid: "f2713 ...

What is the best method to transfer text entered in one textarea to the output of another?

I recently picked up JavaScript again and encountered an issue while developing an app. I am struggling to pass input from one textarea to another, where the text should be converted to uppercase. I attempted to tweak code from w3, but I prefer to achieve ...

How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. Whil ...

Implementing auto-population of input field in Vue JS based on dropdown selection

I'm in search of a solution for automatically filling input fields in Vue.js. My form consists of various input types such as text, select dropdowns, and quantities. I want the vCPU, vRAM, and Storage Capacity fields to be filled with predefined value ...

What are the best practices for managing user forms and uploading files?

How should data in text fields and file upload fields be handled according to best practices? This question is a more generalized version of one I previously asked, which can be found here. Let's consider the scenario of a user registering an accoun ...

AngularJS does not recognize a dynamically created array when using ng-include with ng-repeat

Issue with ng-repeat Directive I have encountered a problem where the ng-repeat directive does not track the addition of a new array, specifically 'options'. This issue arises when the directive is used within a template displayed using ng-dialo ...

Utilizing distinct useState for mapped elements

I am struggling to find a solution on how to pass specific useState states to respective mapped elements. export const Polska = () => { const [riverVisible, setRiverVisible] = useState(false) const [mountainVisible, setMountainVisible] = useState(fa ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

Node application experiencing issues retrieving SVG files during production

When testing my application locally, the svg files display correctly with the code below (Angular.js variables are used within curly brackets): <img ng-src="img/servant_{{servant.personality}}.svg" draggable="false"> However, once deployed on Herok ...

Currently, I am encountering a problem as I attempt to iterate through a dynamic table

I have a table containing various elements. An example row is Jack Smith with multiple rows like this: col1 col2 col3 col4 col5 col6 col7 col8 jack smith 23 Y Y error error_code error_desc The table is ...

Out of Sync Promise Chain

I recently encountered an issue with promise chaining in JavaScript, specifically while working with Vue.js. Here is my code: I have an addItem function that inserts an item into the database. My goal is for this function to first insert the data into the ...

Ways to determine if a browser is currently loading a fresh webpage

I'm experiencing an issue with my web app where the 'safety' code triggers a page reload if the server (Socket.IO) connection becomes silent for more than 5 seconds, often due to customer site firewall or broken-proxy issues. Although the S ...

Unable to successfully update DIV content in JavaScript due to incorrect file path specified

I came across this code online and it seems to be functioning properly. However, no matter what name I give the file that is supposed to load into the DIV, I consistently receive an error message stating "Object was not found." What specific steps do I nee ...