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

117
Visualizações
Concurrent Array Functions

I have a function that takes an array of sub-arrays containing number strings and returns an array with the highest number from each sub-array:

const largestOfFour = arr => {
            arr.map(e => {
                e.sort((a,b) => b - a).splice(1);
            });
            return arr.flat();
        } 

It works perfectly in the way it is formatted above but it does not work if it is formatted with concurrent functions on the array passed in. Like this:

const largestOfFour = arr => {
            return arr.map(e => {
                e.sort((a,b) => b - a).splice(1);
            }).flat();
        }

In that format it returns an array of appropriate length but each element is null. Can anyone help me understand why that is? I usually don't have a problem chaining concurrent functions onto an array.

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

0

There is no concurrency in JavaScript. But your map callback does not return anything (there is no return in the statement block) so .map() returns an array of undefined values.

To avoid that the original data gets mutated, I would also avoid the use of sort on the original array, and use slice instead of splice.

But as you only need one value from each array, you don't even need slice: just get the value at index 0 (making flat unnecessary):

let a = [
  ["1", "2", "3"],
  ["4", "5", "6"]
];

const largestOfFour = arr =>
  arr.map(e =>
    [...e].sort((a, b) => b - a)[0]
  );

console.log(largestOfFour(a));

Or even better, just use Math.max, which also makes the conversion to number:

let a = [
  ["1", "2", "3"],
  ["4", "5", "6"]
];

const largestOfFour = arr => arr.map(e => Math.max(...e));

console.log(largestOfFour(a));

about 4 years ago · Juan Pablo Isaza Relatório

0

The inner block (in map) issn't returning anything, resulting in an array of undefined. Fixed in the snippet...

let a = [
  ["1", "2", "3"],
  ["4", "5", "6"]
]

const largestOfFour = arr => {
  return arr.map(e => {
    return e.sort((a, b) => b - a)[0];
  }).flat();
}

console.log(largestOfFour(a))

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