How to extract keys with the highest values in a JavaScript hashmap or object

Here is an example for you to consider:

inventory = {'Apple':2, 'Orange' :1 , 'Mango' : 2}

In this inventory, both Apple and Mango have the maximum quantity. How can I create a function that returns both Apple and Mango as the answer?

I attempted something like this :

Object.keys(inventory).filter(function(item) { return inventory[item] === Math.max(...Object.values(inventory)); });

However, this only gives one result which is Apple.

Answer №1

To enhance efficiency, one could consider optimizing the process by calculating the maximum value in a more streamlined manner and then executing the filtering operation:

const data = {Apple: 2, Orange: 1, Mango: 2};
const maxValue = Object.keys(data).reduce((accumulator, currentValue) => Math.max(accumulator, data[currentValue]), -Infinity);
const filteredResults = Object.keys(data).filter(currentValue => data[currentValue] === maxValue);

console.log(filteredResults);

This method maintains simplicity and readability while striving for greater operational efficiency.

Answer №2

To ensure your reduce function returns an array of values instead of a single value, initialize the result as an empty array.

Within the function, start by comparing each key with the current longest key to determine if it should replace the existing value in the array.

If the array is empty or all keys have the same value, add the key to the array.

Consider using more descriptive names for your arguments to improve readability and understanding.

Object.keys(hash).reduce(function(longestKeysArray, currentKey){
  if(hash[currentKey] > hash[longestKeysArray[0]]){
    longestKeysArray.length = 0;
  }

  if(longestKeysArray.length === 0 || hash[currentKey] === hash[longestKeysArray[0]]){
    longestKeysArray.push(currentKey);
  }

  return longestKeysArray;
}, []);

Answer №3

To change the object into one with properties that match the count, where the values are the original property names in an array, and then retrieve the value of the property with the highest count:

const hash = {'Apple':2, 'Orange' :1 , 'Mango' : 2};
const indexedByCount = Object.entries(hash).reduce((a, [key, val]) => {
  if (!a[val]) a[val] = [];
  a[val].push(key);
  return a;
}, {});
console.log(
  indexedByCount[Math.max(...Object.keys(indexedByCount))]
);

A method that is less functional but more efficient involves keeping track of a max variable representing the maximum value encountered so far:

const hash = {'Apple':2, 'Orange' :1 , 'Mango' : 2};
let max = -Infinity;
console.log(
  Object.entries(hash).reduce((a, [key, val]) => {
    if (val > max) {
      max = val;
      return [key];
    }
    if (val === max) a.push(key);
    return a;
  }, [])
);

Answer №4

This method is effective. In case the value of max changes, it will clear the previous result and update with only the newly assigned maximum value.

var hash = {'Apple':2, 'Orange':1 , 'Mango':2, "Jackfruit":10, "Pineapple":5, "Tomato":-4};
var max="";

var result = Object.keys(hash).reduce(function(acc, val){
    if(max < hash[val]) (max=hash[val], acc={});
    if(hash[val]==max) acc[val] = hash[val];
    return acc;
},{});

console.log(result)

Answer №5

It is required to traverse the array only once and generate an array of keys as the result

const hash = {'Apple':2, 'Orange' :1 , 'Mango' : 2};
let max = 0;
let result = [];

Object.getOwnPropertyNames(hash).forEach(k => {
  if (hash[k] > max) {
    result = [k];
    max = hash[k];
  } else if (hash[k] === max) {
    result.push(k);
  }
});

console.log(result);

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

Ways to create a table with columns from various fields obtained through an API call

Looking to preprocess data received from an API, the raw data is structured as follows: Desiring to dynamically generate a table with columns based on the fields task_name and saved_answers. It's important to note that saved_answers might contain var ...

Resetting the quiz by utilizing the reset button

Hello everyone, I'm new to this platform called Stack Overflow. I need some help with my quiz reset button. It doesn't seem to be working as intended. According to my code, when the reset button is clicked at the end of the quiz, it should bring ...

Generate a binary string using JavaScript and then transform it into C#

I have an upload section in my JavaScript program. I utilize JS FileReader to obtain a binary string of the uploaded document before sending it to my C# WebApi for storage on the server. JavaScript Code let myFile = ev.target.files[0]; if(myFile.size > ...

The fixed element alters its color when applied to a specific class within a div

I have a button with an icon and text that remains fixed on my webpage. The background colors of the sections change as you scroll through them, alternating between dark and light. I am looking for a solution where I can apply a class to multiple section ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

Deliver JSON from Node.js to the client

I am a beginner in the world of Node.js and JavaScript, facing a challenge that I can't seem to overcome. Currently, I have a Node application set up with Express. The issue at hand involves a script that sends JSON data to my server, which is then s ...

Steps to redirect to a webpage by clicking on an image without relying on anchor tags

Is it possible to redirect to a new webpage without using an anchor tag when someone clicks on an image? Below is my code for the image. <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/368px-Google_2015_l ...

Is there a way to eliminate validation-on-blur errors triggered by onBlur events?

I am currently working on a v-text-field that has the capability to handle simple math expressions like 1+1 and display the correct result (2) when the user either presses enter or moves away from the text field. Here's the code I have implemented so ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

What was the reasoning behind Mozilla's decision to implement a conditional catch clause?

Discover the unique Conditional Catch Clauses from Mozilla Delve into this question out of pure curiosity - why would Mozilla venture beyond standard structures with this innovative feature? What specific challenges or issues is it designed to address? W ...

Is it possible to use Vuelidate for password validation in Vue.js?

I found a helpful reference on How to validate password with Vuelidate? validations: { user: { password: { required, containsUppercase: function(value) { return /[A-Z]/.test(value) }, containsLowercase: fu ...

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS fun ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...

Retrieve the origin of the copied text

While working on a Vue application, I'm curious to know if it's possible to access the source of pasted text. For example, whether the pasted text originated from your own application, Word, or Notepad? I attempted the code below but was unable ...

Dragging and dropping elements on the HTML Canvas with the added feature of snap functionality

I have implemented a drag-and-drop circle feature inside an HTML canvas with the following code: var c = document.getElementById('myCanvas'); var ctx = c.getContext('2d'); width = c.width = window.innerWidth * 0.9; height = c.height ...

What is the reason I am unable to upload personalized templates using <script> elements?

I have a dilemma where I need to swap out multiple templates from a library with my own custom ones without forking the original templates. When I include the templates in my index.html page like: <script type="text/ng-template" id="first-template"> ...

Aframe Descend Rotation

I am currently working on a project in Aframe and I'm looking to implement a control/event that enables an entity to rotate downward. While attempting to create a new animation and add it as a child object to the entity, I have achieved successful re ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

The button will be disabled if any cells in the schedule are left unchecked

I am seeking help on how to dynamically disable the save button when all checkboxes are unchecked. Additionally, I need assistance with enabling the save button if at least one hour is selected in the schedule. Below is my code snippet for reference: htt ...