tips for obtaining the highest value among multiple keys within an array

How can I find the maximum value among multiple keys in an array?

I previously attempted to find the maximum values for just three keys.

getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) {
    var val1 = Math.max.apply(Math, values.map(function (a) { return a[key1] }));
    var val2 = Math.max.apply(Math, values.map(function (a) { return a[key2]; }));
    var val3 = Math.max.apply(Math, values.map(function (a) { return a[key2]; }));
    if (val1 >= val2 || val1 >= val3) {
        return val1;
    } else if (val2 >= val3 || val2 >= val1) {
        return val2;
    }
    return val3;
}

However, I realized that using this approach requires more conditions and code when dealing with multiple keys. Thus, I explored the following solution:

Math.max.apply(Math, values.map(function (a) { return a[key1], a[key2], a[key3]; }));
                                         // here I attempt to use multiple keys 

Unfortunately, this approach did not work as expected. Is there a single line of code available for finding the maximum value among multiple keys in an array?

Answer №1

Array#map each element to its highest value, then determine the maximum value in the array:

var values = [{ a: 4, b: 3 }, { a: 2, b: 8 }, { a: 1, b: 2 }];

var key1 = 'a', key2 = 'b';

var result = Math.max.apply(Math, values.map(function (element) { return Math.max(element[key1], element[key2]); }));

console.log(result);

If you require a more versatile solution that can handle multiple keys:

var values = [{ a: 4, b: 3, c: 23 }, { a: 2, b: 28, c: 13 }, { a: 1, b: 2, c: 1 }];

function getMaxOfKeys(values, keys) {
  return Math.max.apply(Math, values.map(e) {
    return Math.max.apply(Math, keys.map(k) {
      return e[k];
    });
  });
}

// or the ES6 equivalent

const getMaxOfKeysES6 = (values, keys) => 
  Math.max(...values.map(
    (e) => 
      Math.max(...keys.map((k) => e[k]))
    )
  );

console.log(getMaxOfKeys(values, ['a', 'b', 'c']));
console.log(getMaxOfKeysES6(values, ['a', 'b', 'c']));

Answer №2

(I prefer plain ES6 over TypeScript)

Suppose you have an object called values and a specific set of keys that you want to compare, like so:

let values = [
   { key1: 2, key2: 3, key3: 0 },
   { key1: 10, key2: 0, key3: 5 }
];

For each key provided, identify the maximum value within each object and return those as an array. Then find the highest value within that array.

function getMaxValuefromkeys(values, ...keys) {
    return Math.max(...keys.map(key => Math.max(...values.map(o => o[key]))));
}

You can implement this function as follows:

let max = getMaxValuefromkeys(values, 'key1', 'key2', 'key3');

Alternatively, if you have an array of keys:

let max = getMaxValuefromkeys(values, ...keys);

Answer №3

Using the Math.max method in combination with the map function allows us to find the maximum value between two specific keys in an array of objects.

It's important to note that

return a,b;

The comma operator used here simply returns b.

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

Issue encountered while trying to update field using dynamically created row

I am encountering a problem while trying to update the unit cost and total cost of dynamically generated rows in an inventory form that submits inventories to a database. The product names are fetched via autocomplete jQuery, as shown in the snapshots belo ...

Incorporate the Angular library into my project privately without the need to publish

I have developed an Angular library called My-lib and I want to integrate it into my application named My-app without publishing it to the NPM repository. I attempted to use the npm link command after building My-lib with npm link /folder/My-lib/dist/My-l ...

Error: The property 'combine' of 'winston_1.default.format' cannot be destructured since it is not defined

Encountered an error while using Winston in Node.js, how can we resolve it? The version of Winston I am using is 3.3.3 and winston-daily-rotate-file version is 4.5.0 I attempted npm i winston@next --save, but the error persists. ** Here is the Error Mes ...

Using jQuery to attach events and trigger them

Within my code, I have the following scenarios: $("#searchbar").trigger("onOptionsApplied"); And in another part of the code: $("#searchbar").bind("onOptionsApplied", function () { alert("fdafds"); }); Despite executing the bind() before the trigge ...

Expand the clickable area of the checkbox

Is it possible to make clicking on an empty space inside a table column (td) with checkboxes in it check or uncheck the checkbox? I am limited to using only that specific td, and cannot set event handlers to the surrounding tr or other tds. The functional ...

Filtering Array Values within an Object using JavaScript

I need help filtering an object based on array values. For example: { "sun":["sleep","walk"], "mon":["read","dance","ride"], "tue":["work",&q ...

Differences between React's useCallback and useMemo when handling JSX components

I have created a custom component called CardList: function CardList({ data = [], isLoading = false, ListHeaderComponent, ListEmptyComponent, ...props }) { const keyExtractor = useCallback(({ id }) => id, []); const renderItem = useCallba ...

What are the steps to implement character movement in a 2D game using JavaScript?

I'm having trouble getting the image with the ID "yoshi" to move around in my 2D game document.onkeydown = (e) => { if (e.keyCode == 37) yoshi.style.left = yoshi.offsetLeft - 5 + "px"; else if (e.keyCode == 38) yoshi.style.top = yoshi.offset ...

JavaScript interval setting multiples

In my current situation, I have implemented a setInterval based code that continuously checks the value of an AJAX call response. Here is how it looks: var processInterval = setInterval(function () { var processResult = getVideoStatus(data.file_name) ...

Adjusting the width of the dropdown menu in Angular UI

I have set up an Angular UI dropdown list in this plunk, where the selection list has a maximum height and allows for scrolling. However, I am having trouble setting a maximum width for the list. Can anyone suggest how to solve this issue? Below is the HT ...

Dynamically generating an array and seamlessly inserting it into a MySQL database using PHP

I am looking to generate an array that will be used in an insert query, similar to the following: $data=array( 'db_field1'=>$value, 'db_field2'=>$value, 'db_field3'=>$value, and so forth ); $this->db->inser ...

Is there a way to dynamically shift arrow key focus onto buttons in Angular using the left and right arrow keys?

I am facing an issue where pressing the arrow keys left and right does not focus or allow me to navigate through these buttons using the arrow keys. However, when checking the keycode values, they are printed according to the key pressed. I would like to k ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

What is the correct way to bring in a utility in my playwright test when I am working with TypeScript?

I am working on a basic project using playwright and typescript. My goal is to implement a logger.ts file that will manage log files and log any logger.info messages in those files. To set up my project, I used the following commands and created a playwri ...

Instructions for showcasing a 404 error page in the event that a back-end GET request to an API fails due to the absence of a user. This guide will detail the process of separating the

I am currently working on an application that combines JavaScript with Vue.js on the front-end and PHP with Laravel on the back-end. When a GET request is made from the front-end to the back-end at URL /getSummoner/{summonerName}, another GET request is t ...

What steps do I need to take to execute a browserify-ed application in NodeJS?

I have an interesting challenge on my hands - I need to modify a sizable JavaScript codebase to be compatible with NodeJS. The current code follows the CommonJS style and utilizes a gulp build process involving browserify and deamdify. While I am somewhat ...

Expanding the visual in a spacious display with the help of ng-carousel from the Bootstrap framework

I have created a slider with multiple images on a website using Angular 4. The slider is displayed in a small area of the webpage and I would like to add a feature where the user can click on an image to view it in a larger screen or window. This could i ...

Can you suggest an efficient method for routing with EJS templates on an Express server without constantly repeating code?

Assuming my app consists of two views: index.ejs and profile/index.ejs, I aim to set up routing using express code as shown below. /* GET home page. */ router.get('/', function (req, res, next) { res.render('index'); }); /* GET pr ...

Touch interaction operates differently than mouse movement

Imagine three neighboring divs, div1, div2, and div3. When I click on div1 and then move my mouse to div2, the mousemove event is triggered with div2 as the target. However, on mobile devices, if I tap on div1 (touchstart) and slide my finger to div2, the ...

Is it possible for Angular's IVY Compiler to inject classes from external packages?

Our team specializes in building numerous universal packages that are free from Angular dependencies. We use our own @injectable decorator to decorate the classes in these packages, and TypeScript emits metadata for types. "experimentalDecorators": true ...