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

180
Vistas
Javascript sort array outer values to innner values

I don't really know how to articulate this problem, which is probably why I didn't find anything when I googled it, so if you wanna retitle this or direct me to a post that already does what I'm after I'd be grateful.

Anyway, I want to sort an array as follows:

let array = [1, 2, 3, 4, 5];
let sorted = array.sort(someFunction);

console.log(sorted); // -> [1, 5, 2, 4, 3]

array = [1, 2, 3, 4];
sorted = array.sort(someFunction);

console.log(sorted); // -> [1, 4, 2, 3]

See how it grabs the outer-most elements first (1 & 5), then goes for the next nearest level (2 & 4) and then ends up with the middle element at the end (3)? That's what I want.

Obviously a solution that uses Array.sort() (or similar one-liner functional approach) is preferable, but I'll take anything that accomplishes this task at this point.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

1) You can easily achieve the solution using shift and pop

function getValue(arr) {
  const result = [];
  while (arr.length) {
    result.push(arr.shift());
    if (arr.length) result.push(arr.pop());
  }
  return result;
}

let array = [1, 2, 3, 4, 5];
console.log(getValue(array));

2) You can also do this using two-pointer algorithm

function getValue(arr) {
  const result = [];
  let start = 0,
    end = arr.length - 1;

  while (start < end) result.push(arr[start++], arr[end--]);
  if (start === end) result.push(arr[start]);

  return result;
}

console.log(getValue([1, 2, 3, 4, 5]));
console.log(getValue([1, 2, 3, 4]));
console.log(getValue([1, 2, 3]));
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this:

let array = [1, 2, 3, 4, 5];

let l = array.length;
let mid = parseInt(l/2);

let sorted = [];
if (l > 2) {
  for (let i = 0; i < mid; i++) {
       sorted.push(array[i]);
       sorted.push(array[l-i-1]);
  }
} else
  sorted = array;

if ((l % 2) != 0) { // add the mid element of the array to the end.
  sorted.push(array[mid]);
}

console.log(sorted); 

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