0

I have a state in React that contains this values :

{
   income 1 : 500,
   income 2 : 300,
   income 3 : 1000
}

This state extend, the customer can add or delete rows in the state, so I need to find in a dynamic way the key/value where the value is the higher in the Object.

I tried this, but it retrieve only the first key/value :

export const maxIncome = (userWalletIncomes) => {
    for (const [key, value] of Object.entries(userWalletIncomes)) {
        return `${key} : ${Math.max(value)}`
    }
}

Any idea ?

3 Answers 3

1

The reason why it returns the first value is because you don't have any conditional logic preventing the return from occurring the first time.

To solve this you need to first find the record with the max value and return that and only return at the end.

export const maxIncome = (userWalletIncomes) => {
    let maxValue = 0;
    let maxKey = '';
    for (const [key, value] of Object.entries(userWalletIncomes)) {
        if(value > maxValue) {
          maxValue = value;
          maxKey = key
        }
    }
    return `${maxKey} : ${maxValue}`
}

The above code can be simplified further but it should make it clear that you need to find the max first before returning.

Sign up to request clarification or add additional context in comments.

Comments

0

Here, you are not providing any condition before returning and you are implementing Math.max on a single value without any comparison.

This solution will work for you

export const maxIncome = (userWalletIncomes) => {
    for (const [key, value] of Object.entries(userWalletIncomes)) {
     if(Math.max.apply(null,Object.values(userWalletIncomes)) === value){
        return `${key} : ${value}`
        }
    }
}

1 Comment

Ok, there were no comparison. Thank you for helping me
0

Take a look at this. sandbox https://codesandbox.io/s/elegant-forest-ik420?file=/src/App.js

You can use an for in to loop through an object

 const salaries = {
    income1: 1000,
    income2: 2000,
    income3: 3000
  };


 const getMax = (data) => {
    let valuesList = []; //The list we're gonna push the values to and then get the maximum out of it
    for (const key in data) { //Looping through
      if (data.hasOwnProperty(key)) { //Check if key exists in the object (optional)
        const element = data[key]; //Get the value of that key and assign it to a variable
        valuesList.push(element); //Push that to the array
      }
    }
    const max = Math.max(...valuesList); //Find the maximum value in the array(array will contain only values of the object)
    return max; //Returning it
  };

and here is how you would call it

 getMax(salaries)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.