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

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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