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.
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; }
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);