Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!