Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda