Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
Javascript Object key sort using moment.js

I have the following object structure

{ "Apr-18" : { ... },
  "Jan-18" : { ... },
  "Feb-18" : { ... },
  ...
}

I am trying to sort the month (MMM-YY) keys so that it shows as follows

{ "Jan-18" : { ... },
  "Feb-18" : { ... },
  "Apr-18" : { ... },
  ...
}

My code for this is below. I am using moment.js to convert the date into its epoch for the sort comparison. I have roughly followed the solution shown here Sort JavaScript object by key However it's not working.

The console.log returns the object as it was, no sorting has occurred. What am I missing?

const object = { 
          "Apr-18" : { "a":"b" },
          "Jan-18" : { "c":"d" },
          "Feb-18" : { "e":"f" }
}

const sortObjectMonths = (obj) => Object.fromEntries(Object.entries(obj).sort( (a, b) => 
     Date.parse(moment(a, "MMM-YY") - Date.parse(moment(b, "MMM-YY")))
));

let sorted = sortObjectMonths(object)
console.log(sorted)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Your code is almost okay but in .sort() the element a and b both are arrays of key and value. Key is at index 0 and value at index 1. Date.parse() won't work and converting the value by using new Date() is suggested. So, your code should be -

const moment = require("moment");

const sort = {
  clientname: {
    "Feb-18": { test: "c" },
    "Jan-18": { test: "a" },
    "Apr-18": { test: "v" },
  },
};

const sortObjectMonths = (obj) => {
  return Object.fromEntries(
    Object.entries(obj).sort(
      (a, b) => moment(new Date(a[0])) - moment(new Date(b[0]))
    )
  );
};

let sorted = sortObjectMonths(sort.clientname);
console.log(sorted);
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use Object.entries() to get the object property keys and values, then use Array.sort() to sort them using moment. We can simply subtract the moment values to sort them.

The Array.sort() accepts two arguments, firstEl, secondEl, in this case that will be [key1, value1], [key2, value2]. We can use destructuring to write these as ([a,],[b,]), where a and b are the object keys (e.g. 'Apr-18').

Then we'll use Object.fromEntries() to get our sorted object.

const object = { 
    "Apr-18" : { "a":"b" },
    "Jan-18" : { "c":"d" },
    "Feb-18" : { "e":"f" },
}

console.log('Original object:', object)

const sortedObject = Object.fromEntries(
    Object.entries(object).sort(([a,],[b,]) => { 
         return moment(a, "MMM-YY") - moment(b, "MMM-YY");
    })
)
console.log('Sorted object:', sortedObject)
        
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

Without moment

const months = ["Jan","Feb","Mar","Apr"]

const object = { 
    "Apr-18" : { "a":"b" },
    "Jan-18" : { "c":"d" },
    "Feb-18" : { "e":"f" },
}


const sortedObject = Object.fromEntries(
  Object.entries(object)
    .sort(([a,],[b,]) => months.indexOf(a.split("-")[0]) - months.indexOf(b.split("-")[0]))
)
console.log('Sorted object:', sortedObject)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda