Tengo un objeto de matriz como
const d = [ { id: 20, text: 'deaf' }, { id: 30, text: 'acta', }, { id: 0, text: 'deema1' }, { id: -1, text: 'deema2' }, ]
Quiero ordenar la matriz por texto pero quiero mantener id -1 y 0 siempre en la parte superior, por lo que el resultado sería
// sorted [ { id: -1, text: 'deema2' }, { id: 0, text: 'deema1' }, { id: 30, text: 'acta' }, { id: 20, text: 'deaf' }, ]
Traté de ordenar como d.sort((a, b) => (a.text).localeCompare(b.text))
pero no estoy seguro de cómo manejar el caso -1 y 0
const d = [ { id: 20, text: 'deaf' }, { id: 30, text: 'acta', }, { id: 0, text: 'deema1' }, { id: -1, text: 'deema2' }, ]; d.sort((a, b) => (a.text).localeCompare(b.text)) console.log(d);
Puedes trabajar con indexOf
:
const d = [ { id: 20, text: 'deaf' }, { id: 30, text: 'acta', }, { id: 0, text: 'deema1' }, { id: -1, text: 'deema2' }, { id: 0, text: 'ace' }, { id: -999, text: 'hello' }, { id: 800, text: 'game' }, ] d.sort((a, b) => [0,-1].indexOf(b.id) - [0,-1].indexOf(a.id) || a.text.localeCompare(b.text)); console.log(d);
Esto ordenará todos los objetos con id
-1 primero, y entre ellos, la propiedad de text
definirá el orden, luego todos los objetos con id
0 (nuevamente ordenados relativamente por text
) y finalmente todos los demás objetos por text
.
En caso de que no desee que haya distinción entre 0 y -1, pero clasifíquelos por text
entre ellos, luego use includes
en lugar de indexOf
:
const d = [ { id: 20, text: 'deaf' }, { id: 30, text: 'acta', }, { id: 0, text: 'deema1' }, { id: -1, text: 'deema2' }, { id: 0, text: 'ace' }, { id: -999, text: 'hello' }, { id: 800, text: 'game' }, ] d.sort((a, b) => [0,-1].includes(b.id) - [0,-1].includes(a.id) || a.text.localeCompare(b.text)); console.log(d);
Puede poner varias condiciones dentro de sort
para obtener el resultado deseado. La primera condición es más importante que la siguiente y así sucesivamente. Así es como se vería:
const d = [{ id: 20, text: 'deaf' }, { id: 30, text: 'acta', }, { id: 0, text: 'deema1' }, { id: -1, text: 'deema2' }, ] const sorted = d.sort((a, b) => { if (a.id === -1) { return -1; } if (a.id === 0) { return -1; } return a.text.localeCompare(b.text); }); console.log(sorted)
Ligeramente modificado de una de las respuestas anteriores para usar el operador de tubería, de esta manera puede agregar cualquier otro número que desee simplemente usando más tuberías.
const d = [ { id: 20, text: 'deaf' }, { id: 30, text: 'acta', }, { id: 0, text: 'deema1' }, { id: -1, text: 'deema2' }, { id: 0, text: 'ace' }, { id: -999, text: 'hello' }, { id: 800, text: 'game' }, ] const sorted = d.sort((a, b) => { if (a.id === -1 || a.id === 0) { return -1; } return a.text.localeCompare(b.text); }); console.log(sorted)