Realmente no sé cómo articular este problema, que es probablemente la razón por la que no encontré nada cuando lo busqué en Google, así que si quieres cambiar el título de esto o dirigirme a una publicación que ya hace lo que busco. estar agradecidos.
De todos modos, quiero ordenar una matriz de la siguiente manera:
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]¿Ves cómo toma primero los elementos más externos (1 y 5), luego pasa al siguiente nivel más cercano (2 y 4) y luego termina con el elemento central al final (3)? Eso es lo que quiero.
Obviamente, es preferible una solución que use Array.sort() (o un enfoque funcional similar de una sola línea), pero tomaré cualquier cosa que logre esta tarea en este punto.
1) Puede lograr fácilmente la solución usando shift y 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) También puedes hacer esto usando un algoritmo two-pointer
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; }Prueba esto:
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[li-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);