Is there a way to choose values from an object array in Angular?

Within my Angular (TypeScript) Project, I am working with an object array.

let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}];

My goal is to extract the minimum value of the min properties and the maximum value of the max properties. To achieve this, I want to create two variables as follows:

let min = // The minimum value from the min properties of all items would be -10;
let max = // The maximum value from the max properties of all items would be 810;

Is there a practical way, using lambda functions or other methods, to accomplish this task?

Answer №1

To retrieve all the minimum and maximum values, you can utilize the map function along with Math.min and Math.max.

let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}];

let min = Math.min(...a.map(o => o.min));
let max = Math.max(...a.map(o => o.max));

console.log(min);
console.log(max);

Alternatively, another method is to use reduce, which only requires looping through the array once.

let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}];

let min = a.reduce((c, v) => v.min < c ? v.min : c, 0);
let max = a.reduce((c, v) => v.max > c ? v.max : c, 0);

console.log(min);
console.log(max);

Answer №2

Calculate the minimum value by using Math.min on a list of items and their minimum values.
Similarly, find the maximum value by applying Math.max to a collection of items and their maximum values.

Answer №3

Check out this method:

const values = [{low: 0, high: 10},{low: 10, high: 810},{low: -10, high: 110}];

    const minimum = Math.min(...values.map(item => item.low));
    const maximum = Math.max(...values.map(item => item.high));

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

Invoking a function from a separate JavaScript file and finding out that an object is considered null

The source code for a word game is stored in Main.js file. Currently, I am attempting to introduce another file called Bookmarks.js (included on the web page prior to the Main.js file). This new file will contain an object var bookmarks = {}; that stays s ...

Having trouble getting the Angular Route to work, any tips on how to fix it?

I am currently learning Angular and have encountered a small issue. When I place the Component in my app.component.html as shown below, it functions correctly: <body> <div class="container"> <app-search-books></app-search-books ...

What is the best way to resize an image to fit its surroundings within a nested box?

Have you ever heard of a website called SPAM? It has a unique homepage that I want to replicate using JavaScript, jQuery, and some CSS. My main challenge is figuring out how to adjust the image size to match the center box on the page. I want to create th ...

Using React and Material-UI to dynamically populate a table with data retrieved from

Material ui table utilizes data in a specific format. rows: [ createData(1, "dashboard", "details"), createData(2, "product", "product details"), ].sort((a, b) => (a.id < b.id ? -1 : 1)) When the API responds with data stored in st ...

Tips for implementing the new useState value in your code

Using DataGrid Material UI, I am facing an issue where the selected row is not being deleted when clicking on the delete button. The problem arises from setting the ID value in the useState hook and encountering asynchronous behavior in deleting the rows. ...

What might be causing the attribute of this Backbone model to be undefined when attempting to access it?

I have a straightforward REST API that provides information about an item at /api/items/:id, which includes the ID and name. I am using a Router to organize my Backbone views. The edit route creates a FormEditItem view, passing the ID from the URL. To ret ...

Error encountered when attempting to run an Angular 2 application with 'ng serve' command

Initially, I installed angular-cli using the command npm install -g angular-cli and then proceeded to create an angular-cli project. Following that, I used the command ng new Angular2TestProject to create a project and changed the directory to Angular@Test ...

What is the best way to enable and disable the edit-in-place feature using jQuery?

Recently, I decided to experiment with the jQuery In Place Editor but I've come across an issue I can't seem to solve. Below is the code snippet that I have been working on. In my implementation, I am utilizing the jQuery toggle method to enable ...

The error message "The type 'MouseEvent' is non-generic in TypeScript" popped up on the screen

Having created a custom button component, I encountered an issue when trying to handle the onClick event from outside the component. I specified the parameter type for the onClickCallback as MouseEvent<HTMLButtonElement, MouseEvent>, which is typical ...

The chosen Angular material pre-built theme of indigo-pink does not seem to be applied properly

Within my styles.scss @import '~@angular/material/prebuilt-themes/indigo-pink.css'; I have also attempted this in my index.html <link href="node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet" /> Finally, I m ...

Issue with React component not updating

Experiencing an issue in a React code related to nested components within React. Link to code The problem arises from having a parent component called "testing" with two child components, Component1 and Component2, each with Component3 as a sub-child und ...

Learn the steps to Toggle Javascript on window resize

Is there a way to toggle Javascript on and off when the window is resized? Currently, resizing the window causes the navigation bar to stick and remain visible above the content. <script> if ( $(window).width() <= 1200 ) { }else{ $('nav& ...

Applying the power of Angular function binding within .html() function in d3 visualizations

I am attempting to create a clickable d3 foreignObject span that triggers a function in the component TypeScript file. Below is a snippet of the code I have been working on: .append("foreignObject") .attr("x", x) .attr("y" ...

What could be the issue with my code? (Threejs spotlight shadow)

I recently created a Three.js scene featuring two cubes on a plane. The spotLight I placed in the top-left corner is intended to look at the coordinates 50, 0, -50. However, I noticed that the shadows appear odd and the light does not seem to be focusing ...

Unable to access array in the result of a Node.js Mongoose find populate operation

I have the following code in my backend: ad = await Ad.find({'company': companyId}).populate('creator'); When I console.log(ad), this is what I get: [ { connections: [], status: 1, _id: 6047c711b1f8cf1c98b2227c, title ...

What is the best way to use hasClass in a conditional statement to display text based on the content of a different div element?

Let's say we have the following HTML code: <div>New York</div> Now, we want to add another div like this: <div>Free Delivery</div> How can we achieve this using JavaScript? ...

When the mobile navigation bar is tapped, it remains open instead of closing

The persistent challenge of the mobile navbar failing to close upon clicking an item continues to baffle. Numerous attempts from Stack Overflow and even tweaks recommended by ChatGPT have been futile in resolving this issue. Despite trying alternative me ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

Is there a way to make a mat-form-field read-only?

Is there a way to make mat-form-field read-only in Angular for a view that allows users to read but not edit the content? ...

Choose a word at random from a JSON string

Utilizing JSONP, I have successfully retrieved a list of words from an external source to randomly select one for use in a game. The current source being used is as follows: function processResult(obj) { console.log(obj); var data = ...