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

Transmit the Boolean value to the controller using ajax requests in asp.net.core with C# programming

Within the view section, there is a form that includes a checkbox input. <div class="checkbox"> <label class="">active</label> <div class="icheckbox_flat-green checked" style="position: relative;"> <input type="checkbox" id="A ...

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

Solving repeated function firing with ng-checked in an AngularJS ng-repeat loop

In the HTML code below, there is an ng-repeat that creates checkboxes: <span ng-repeat="name in $ctrl.widgetSelectorNames" class="widget-selectors"> <label class="checkbox" for="{{name}}"> <input type="checkbox" value="{ ...

Angular controller utilizing the `focusin` and `focusout` events from jQuery

Can anyone help me figure out why this piece of code is generating syntax errors in my AngularJS controller? $(".editRecur").focusin(function() { $(.recurBox).addClass("focus"); }).focusout(function() { $(.recurBox).removeClass("focus"); }); ...

IE and Firefox display different responses when encountering an empty XML document

When working with jQuery to read an XML file, I occasionally encounter the situation where the XML is empty. In this case, I anticipate that the error function (no_info) will be triggered because the file is not formatted as expected for the dataType. Int ...

pagination functionality incorporated into element ui tables

Issue with Element UI: when a checkbox is selected and the page is changed, the selected rows' checkboxes are removed. I need to retain the selection items while paging so that users can select items from multiple pages without losing the selections f ...

Tips for saving an image that has been dragged onto the browser locally

I recently started working with Angular and decided to use the angular-file-upload project from GitHub here. I'm currently in the process of setting up the backend for my application, but I'd like to be able to display dropped files locally in th ...

Experience interactive video playback by seamlessly transitioning a webpage video into a pop-up when clicking on an

I want to have a video play as a pop-up when the user clicks a play button, while also fading out the background of the page. It should be similar to the way it works on this website when you click to watch a video. How can I achieve this? <div class=" ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

Unable to alter a global variable while iterating through an angular.forEach loop

I've encountered a challenge while attempting to modify a global variable within an Angular.forEach loop. Although I can successfully update the variable within the loop, I'm struggling to maintain those changes when accessing the variable outsi ...

Guide on altering the background color of a table row depending on the data in its cells with the help of AngularJS

I am looking to dynamically change the background color of a row based on specific cell data. If the first four characters in a table cell match a certain value, I want the entire row to change its color to red. Currently, my code changes the row color ba ...

Organizing multiple <image> tags into an array with Javascript - a beginner's guide!

My HTML file contains multiple images. When a user clicks on them, their IDs should be captured without any issues. I am looking for help with the following tasks: 1) Storing all clicked image IDs in an array For example: array = img01 ; array = img ...

Problematic redirect following jQuery AJAX request

I am facing an issue with my code where the page is redirected to the index page of my website after the AJAX method completes, but the redirected page appears empty with just a background. function login(){ var uname = document.getElementById("UserNa ...

How do I create individual tables for each JSON array within my object using React and MaterialUI?

I have a unique challenge with a component that creates multiple tables, all within one <TableContainer>. The issue lies in the fact that every table is confined within the same container and I am unable to customize each table separately. Each tabl ...

"Sending a file (Image) through NextJS API Routes to an external API: A step-by-step guide

I am currently using a combination of NextJS (SSR and SPA for authorized dashboard) with Django Rest FW on the backend. To handle authentication, I employ JWT tokens stored in cookies. As a result, it is necessary to have a middleware at /pages/api/* that ...

Unable to process JavaScript function

Still in the process of developing my "mvc/social" PHP project, I am currently focusing on securing user input for the status message. I have created both a PHP and JavaScript function for this purpose, but it seems like the JavaScript function is not bein ...

Is jquery.validate showing errors more than once?

For my testing program, I utilize the jquery.validate plugin to validate user input fields. Here is how it's set up: <script src="js/jquery-1.12.4.min.js"></script> <script src="js/jquery-form-3.51.min.js"></script> <script ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

Discover the following `<td>` identifier through the act of clicking on a separate `<td>` element

I have a few td's with specific ids: <td id="first">first</td> <td id="second">second</td> <td id="third">third</td> <td id="fourth">fourth</td> Whenever I click on one of the td elements, I want to re ...

Is there a way to add pins to separate entity layers, and then remove them from a specific entity layer using Bing Maps AJAX Control, Version 7.0?

Currently, I am utilizing Bing Maps to display store locations on a map. The information about the stores is coming from a dynamic JSON response. When the page loads, the map shows local stores with pushpins and infoboxes. As the map pans, my goal is to re ...