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

136
Visualizações
Find the middle element in an array

Please help me write a function that will find the middle element of an array according to the following rule:

['a','b','c'] => 'b'
['a','b','c','d'] => 'b'
['a','b','c','d','e'] => 'c'

extreme cases:

[] => null
['a'] => 'a'
[null] => undefined
['a',null,'c'] => 'a'
['a','b','c',null, null] => 'b'

Here's what I was able to do, but it doesn't work quite right:

function findMidlle(arr)
{
    if(arr.length % 2 == 1) {
        return arr[(arr.length-1)/2];
    } else {
        return (arr[(arr.length/2)]+arr[(arr.length/2 -1)])/2
    }
}

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

0

Options

  • Math.floor((arr.length - 1) / 2) to always have the element at the center (or before)
  • Math.floor(arr.length / 2) to always have the element at the center (or after)

Example

function middle(arr) {
    return arr.length ? arr[Math.floor((arr.length - 1) / 2)] : undefined;
}

function middle(arr) {
    return arr.length ? arr[Math.floor((arr.length - 1) / 2)] : undefined;
}

console.log(middle(['a','b','c']));
console.log(middle(['a','b','c','d']));
console.log(middle(['a','b','c', 'd', 'e']));

Solution

In your specific case you are requesting some additional conditions:

function middle(arr) {
    return arr.length ? arr[Math.floor((arr.length - 1) / 2)] : undefined;
}

function specialMiddle(arr) {
    if (!arr.length) return null;
    if (arr.length === 1 && arr[0] === undefined) return undefined;
    else return middle(arr.filter(a => a !== null /*&& a !== undefined*/));
}

console.log(specialMiddle([]));
console.log(specialMiddle(['a']));
console.log(specialMiddle([null]));
console.log(specialMiddle(['a', null, 'c']));
console.log(specialMiddle(['a', 'b', 'c', null, null]));

about 4 years ago · Juan Pablo Isaza Relatório

0

You have quite an interesting set of particular cases, especially the ones:

[] => null
[null] => undefined

And from the others I get that you need to start by filtering the array

['a',null,'c'] => 'a'
['a','b','c',null, null] => 'b'

So here's my try:

function findMiddle(arr) {
  if (arr.length == 0) return null;
  const filteredArr = arr.filter(x => x);
  const len = filteredArr.length;
  
  return (len == 0)?undefined
         : (len%2 == 0)?filteredArr[(len/2)-1]
         : filteredArr[Math.floor(len/2)]
 
}


function easyLog( shouldBe, itIs ) {
  console.log("sould be: ",shouldBe," it is: ",itIs);
}


// ['a','b','c'] => 'b'
easyLog('b',findMiddle(   ['a','b','c']   ));
//['a','b','c','d'] => 'b'
easyLog('b',findMiddle(   ['a','b','c','d']   ));
//['a','b','c','d','e'] => 'c'
easyLog('c',findMiddle(  ['a','b','c','d','e']    ));
//extreme cases:

//[] => null
easyLog('null',findMiddle([]));
//['a'] => 'a'
easyLog('a',findMiddle(   ['a']   ));
//[null] => undefined
easyLog('undefined',findMiddle([null]));
//['a',null,'c'] => 'a'
easyLog('a',findMiddle(   ['a',null,'c']   ));
//['a','b','c',null, null] => 'b'
easyLog('b',findMiddle(   ['a','b','c',null, null]   ));

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