Home > Software engineering >  How to return the name of the variable with maximum value from an array using Javascript
How to return the name of the variable with maximum value from an array using Javascript

Time:03-02

I have been trying to return a instead of 100 in Javascript?

However, I believe I am doing something wrong with my loop.

let a = 100
let b = 25
let c = 75
let d = 50
let A = [a,b,c,d]

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    let result = []
    let max = Math.max(...A)
    for (let i = 0; i < A.length; i  )
    if (A[i] === max){
      return A[i]
    }
    return A
}
console.log( solution(A))

CodePudding user response:

As @user1599011 mentioned, this is not possible using an array as your example.


I'd recommend using an object, with the key's as desired, and the value as the integer. We can use the the shorthand object syntax to create the object like so:

let A = { a, b, c, d };

Then you can use reduce() on Object.keys() to search for the key with the heights value:

let a = 100
let b = 25
let c = 75
let d = 50
let A = { a, b, c, d };

function solution(A) {
    return Object.keys(A).reduce((prev, cur) => A[prev] > A[cur] ? prev : cur);
}

console.log(solution(A)); // a

CodePudding user response:

As has been pointed out use an object. Pass that object to solution(); one way you can find and return the key of the highest value is to use Object.entries() to produce an array with [key, value], eg [a,100], as elements, sort by value in descending order then return the key of element in index 0.

let a = 100;
let b = 25;
let c = 75;
let d = 50;
let A = {a,b,c,d};

function solution(A) {
    return Object.entries(A).sort((a, b) => b[1] - a[1])[0][0]
}
console.log( solution(A) )

NOTE: If there are multiple keys with the highest value, this will return only one key.

  • Related