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

88
Visualizações
Most efficient way to compare multiple arrays based on a fixed element and copy the largest one?

I've four arrays of length 18 (k1,k2,k3&k4). I want to compare the last element of each array & copy the contents of the array with the largest final element.

Currently, this is how I'm doing it:

if (this.k4[17]>=this.k1[17] && this.k4[17]>=this.k2[17] && this.k4[17]>=this.k3[17])
            m = this.k4.filter(() => true);
        else if(this.k1[17]>=this.k4[17] && this.k1[17]>=this.k2[17] && this.k1[17]>=this.k3[17])
            m = this.k1.filter(() => true);
        else if(this.k2[17]>=this.k4[17] && this.k2[17]>=this.k1[17] && this.k2[17]>=this.k3[17])
            m = this.k2.filter(() => true);
        else
            m = this.k3.filter(() => true);

But this isn't scalable incase I added more arrays in the future.

Here is another method:

var maxlast = [this.k1[17],this.k2[17],this.k3[17],this.k4[17]];
var max = maxlast.reduce(function(a,b){return Math.max(a, b)}, -Infinity);
var pos = maxlast.indexOf(max)+1;
m = eval("this.k"+pos+".filter(() => true);");

I've heard eval() is a major security risk, is there an alternative approach?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use sort and just return the first element of descending sorted list

const arr = [this.k1, this.k2, this.k3, this.k4]
// sort desc
const arrayHasMaxLastElement = arr.sort((a, b) => b[b.length - 1] - a[a.length - 1])[0]
about 4 years ago · Juan Pablo Isaza Relatório

0

Another way to get max item with reduce

const arr = [[1,2,3], [3,4,5], [4,5,6], [7,8,9]];

const result = arr.reduce((max, item) => max.at(-1) > item.at(-1) ? max : item);

console.log(...result);
.as-console-wrapper{min-height: 100%!important; top: 0}

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