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

190
Visualizações
Based on Array#reduce how does one identify the array item which matches best some specific constraints?

Basically what I'm trying to do is map this array and identify which objects satisfy a certain condition. The condition is: Get an object that has the highest value of a+b and if you have two objects with the same value of a+b, get the one that has the highest value of c. What is the best way to do this? Maybe reduce?

   const data = [
      {
        id: 1,
        a: 12,
        b: 75,
        c: 11,
      },
      {
        id: 2,
        a: 65,
        b: 14,
        c: 32,
      },
      {
        id: 3,
        a: 32,
        b: 23,
        c: 45,
      },
      {
        id: 4,
        a: 22,
        b: 1,
        c: 3,
      },
    ];
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

A simple for loop should work. Loop through the array and if the current object's a + b is greater than a stored object, overwrite the stored object with the current loop object - checking c if necessary.

about 4 years ago · Juan Pablo Isaza Relatório

0

Already a first naive reduce based approach which implements the OP's requirements and constraints almost literally does exactly what the OP is asking for.

In case one does not provide an initial value to the reducer, this reducing callback function gets passed the first two array items at its first invocation time. The function is supposed to return a value which, with any following iteration step, will be passed as the very functions 1st argument alongside the currently processed array item (which is the 2nd argument).

Thus for the OP's use case one just needs to implement the correct comparison which always ensures the expected return value ...

function getItemWithHighestTotal(result, item) {
  const resultTotal = result.a + result.b;
  const itemTotal = item.a + item.b;
  return (
    ((resultTotal > itemTotal) && result) ||
    ((resultTotal < itemTotal) && item) ||
    ((result.c < item.c) && item) ||
    // OP did not define the clause where
    // even both `c` values are equal.
    result
  );
}

console.log(
  [{
    id: 1,
    a: 12,
    b: 75,
    c: 11,
  }, {
    id: 2,
    a: 65,
    b: 14,
    c: 32,
  }, {
    id: 3,
    a: 32,
    b: 23,
    c: 45,
  }, {
    id: 4,
    a: 22,
    b: 1,
    c: 3,
  }].reduce(getItemWithHighestTotal)
);
console.log(
  [{
    id: 1,
    a: 12,
    b: 75,
    c: 11,
  }, {
    id: 2,
    a: 65,
    b: 14,
    c: 32,
  }, {
    id: 3,
    a: 32,
    b: 23,
    c: 45,
  }, {
    id: 4,
    a: 22,
    b: 1,
    c: 3,
  }, {
    id: 5,
    a: 75,
    b: 12,
    c: 12,
  }].reduce(getItemWithHighestTotal)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

A simple for loop would be great

const data = [
      {
        id: 1,
        a: 12,
        b: 75,
        c: 11,
      },
      {
        id: 2,
        a: 65,
        b: 14,
        c: 32,
      },
      {
        id: 3,
        a: 32,
        b: 23,
        c: 45,
      },
      {
        id: 4,
        a: 22,
        b: 1,
        c: 3,
      },
    ];
    
let index,
  cHigh = Number.MIN_SAFE_INTEGER,
  total = Number.MIN_SAFE_INTEGER;

for (let i = 0; i < data.length; ++i) {
  const { a, b, c } = data[i];
  if (a + b > total) {
    total = a + b;
    index = i;
  } else if (a + b === total) {
    if (c > cHigh) {
      cHigh = c;
      index = i;
    }
  }
}
console.log(index);
console.log(data[index]);

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