Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
How to return the name of the variable with maximum value from an array using Javascript

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))

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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], e.g., [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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!