What is the best way to retrieve the maximum value from an array object in Angular?

i have an array and i'm trying to return the status title from the largest id in that array using Angular. Here's a link to the image: https://i.sstatic.net/87okc.png

I've updated my code as follows:

getData(id){
    let url_detail = this.apiurl + `/${id}`;
    this.http.get<any[]>(url_detail).pipe(
        tap(data=>{
            var status = data.reduce((item, curr) => {
                return item.id < curr.id ? curr : item;
              }).status.title;
        
            return status;
        }),
        catchError(this.handleError)
    );
}

However, when I call this function like this:

console.log("status ", this.service.getData(1))

it only returns undefined. Can someone please assist me with this issue?

Answer №1

Hey @Alma, just a quick tip - instead of using tap, try using map as it doesn't change the response. Also, don't forget to subscribe to the Observable that is returned by HttpClient.get in order to fetch the result. This advice pairs well with what @dork mentioned earlier.

fetchData(id){
    let url_detail = this.apiurl + `/${id}`;
    
    // Make sure to include 'return' here
    return this.http.get<any[]>(url_detail).pipe(
        // Consider using 'map' here instead
        map(data=>{
            var status = data.reduce((item, curr) => {
                return item.id < curr.id ? curr : item;
              }).status.title;
        
            return status;
        }),
        catchError(this.handleError)
    );
}

// Lastly,
this.service.fetchData(1).subscribe(res=>{
   console.log("status: ", res)
})

Answer №2

To retrieve the title of the object with the highest id, you can leverage the power of the array's reduce method in JavaScript.

data.reduce((item, curr) => {
  return item.id < curr.id ? curr : item;
}).status.title;

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

How can I use moment js to convert the current local time to a different timezone with a specified offset?

How should I convert the local time to another timezone? The code below is what I have tried so far: const timezone = 'UTC-0500'; const dateInput = new Date(); let dateTimeExplicit1 = moment.utc(dateInput).utcOffset(timezone).toDate(); The above ...

What is the process for refreshing one observable with data from another observable?

As a complete beginner to these technologies, please bear with me if my question sounds strange and the terminology is not quite right. I have a component that displays data in a table format. export class SourceFieldComponent implements OnInit { ... ...

Counting duplicate values associated with the same key in a JSON array using JavaScript/NodeJS

Hello everyone, I could really use some assistance in solving this issue. If this has already been asked before, please direct me to the original question. Currently, I am working with a JSON array of elements. For example: var data = [{"key":"Item1"},{ ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Utilize custom SCSS styling for Angular component based on specific conditions

Currently, I am attempting to customize the css for an Angular-Material component. To achieve this, I am utilizing encapsulation:ViewEncapsulation.None in order to sidestep using the deprecated /deep/ or ::ngdeep. Thus, my SCSS code appears as follows: . ...

PHP array pushing in multiple dimensions is a crucial aspect of data

I pulled some information from mySQL (Name & Score) and now I need to store it in an array for sorting purposes. $stack = array(); while ($row = mysqli_fetch_array( $db_erg, MYSQLI_BOTH)) { $stack_data = array($row['Name'] => $ ...

The initial load of Angular OpenId Connect triggers the rendering process before the token is fully prepared

I am currently utilizing Angular 10 along with angular-auth-oidc-client (https://github.com/damienbod/angular-auth-oidc-client). My objective is to automatically redirect the user to the authentication server if they are not logged in without displaying a ...

What is the best way to detect object changes in typescript?

Having an object and the desire to listen for changes in order to execute certain actions, my initial approach in ES6 would have been: let members = {}; let targetProxy = new Proxy(members, { set: function (members, key, value) { console.log(k ...

Autocomplete feature in MUI allows filtering to begin after typing at least 3 characters

I've encountered an issue with the Autocomplete MUI component I'm using to filter a list of checkboxes. The popup with options should remain open at all times, but I only want the filtering to be triggered when the user input is more than 3 chara ...

Adding elements to a JSON array within a .json file using PHP - the ultimate guide!

I have a JSON array stored in a JSON file [["a","b","c","d"],["3","2","25","25"],["4","48","20","20"],["3","1","22","22"],["5","4","31","31"],["5","3","33","33"],["5","6","43","43"],["5","8","45","45"],["5","5","42","42"],["5","11","37","37"],["5","7","40 ...

What is the best way to store multiple arrays within an array in Python?

My goal is to create a 5x5 array in Python that will store a total of 25 arrays. Currently, I am attempting to divide an image into 25 pieces using nested loops in openCV. However, I am struggling with saving the cropped images in the slices array. board = ...

Storing an Array of Strings in Shared Preferences

Looking to handle a persistent String Array with multiple rows and one column: * Initially, the String Array should be empty on app launch. * Subsequent executions will populate the Array from a File, keeping its contents available throughout the app. ...

Extract an element from an array in React if it is present

I am facing an issue with using the react immutability helper to manipulate my array. When I try to add or remove items from the array, it keeps adding duplicates of the same item instead of properly handling the addition/removal process. Despite attempti ...

Transforming a Java calendar date into a JavaScript date by utilizing the getTimezoneOffset() method of the new Date object

I've been working with a calendar data that is sent to the server, which includes the following fields: export interface CalendarDate{ dayOfMonth: number; hourOfDay: number; minute: number; month: number; second: number; year: ...

What is the best way to iterate through multiple arrays using a foreach loop in PHP?

Is there a way to send multiple arrays in a foreach() loop? I know the method used in the code below is incorrect. What is the correct approach? $Fname = [1,2,3,4,5]; $Lname = [1,2,3,4,5]; $Addrs = [1,2,3,4,5]; $Mobile = [1,2,3,4,5]; $fields = array( ...

Calculate the number of distinct values in an associative array

Thank you in advance for any assistance. I have dedicated numerous hours scouring through forums and websites to find a solution to my dilemma, but unfortunately, I seem to be struggling with understanding the answers provided or simply haven't stumb ...

What is the best return type to use for a TypeScript function that returns an AsyncFunction?

From my experience, this code should work just fine... let DynamicFunction = Object.getPrototypeOf(dynamic function(){}).constructor; export function generateJsFunction(event: string, body: string[]): any { return new DynamicFunction(body.join("\n ...

Array Connections

There's a bit of a dilemma I'm facing. I might be taking the long route, but honestly, I'm not sure. If you could assist me, I would greatly appreciate it. The issue at hand is that I am uploading photos to FTP and saving the URLs in MySQL ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Use patchValue to assign a value and make the field inactive

After loading a list and pushing it into a FormArray, I am in need of dynamically setting the disabled property for certain fields. My question is: Can I achieve this by using only the patchValue method? I attempted something like this.rowArray.controls[i ...