Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
Sort 2d Array by ascending order using Javascript

I've tried a map and forEach loop and still can't get this to sort by alphabetical order. Not sure what I am missing here.

My array:

const filtData = [
  [
    {
      gameType: "Rowing",
    },
    {
      gameType: "Rowing",
    },
    {
      gameType: "Rowing",
    },
  ],
  [
    {
      gameType: "Golf",
    },
    {
      gameType: "Golf",
    },
    {
      gameType: "Golf",
    },
  ],
  [
    {
      gameType: "Soccer",
    },
    {
      gameType: "Soccer",
    },
    {
      gameType: "Soccer",
    },
  ],
  [
    {
      gameType: "Baseball",
    },
    {
      gameType: "Baseball",
    },
    {
      gameType: "Baseball",
    },
  ],
]

Js:

filtData.forEach(d => d.sort((a,b) => a.gameType - b.gameType))
console.log(filtData) /* <--fails  */

const sortedData = filtData.map((d) => d.sort((a, b) => {
  return a.gameType - b.gameType;
}));
console.log("sortedData", sortedData)/* <--fails  */

JsFiddle: https://jsfiddle.net/eL510oq3/

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

A few points:

  • You're sorting based on strings, not numbers, so use String#localeCompare
  • No need to use forEach or .map, just sort

const filtData = [ [ { gameType: "Rowing", }, { gameType: "Rowing", }, { gameType: "Rowing", }, ], [ { gameType: "Golf", }, { gameType: "Golf", }, { gameType: "Golf", }, ], [ { gameType: "Soccer", }, { gameType: "Soccer", }, { gameType: "Soccer", }, ], [ { gameType: "Baseball", }, { gameType: "Baseball", }, { gameType: "Baseball", }, ], ];

filtData.sort((a,b) => a[0].gameType.localeCompare(b[0].gameType))

console.log(filtData);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Sorting Array Objects in ASC Order Method 1 :

let arrayConcat = filtData.reduce((preValue, curValue) => {
return preValue.concat(curValue)
}, []);

let result = arrayConcat.sort((a, b) => {
  return a.gameType.localeCompare(b.gameType);
})

console.log(result);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda