Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda