Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda