web-dev-qa-db-fra.com

Trier les tableaux par année et par mois

J'ai le tableau ci-dessous,

let  yearAndMonth  =  [
    { "year": 2013, "month": "FEBRUARY" },
    { "year": 2015, "month": "MARCH" },
    { "year": 2013, "month": "JANUARY" },
    { "year": 2015, "month": "FEBRUARY" }
]

Je veux trier le tableau par année d'abord et après ce tri mois de l'année,

Je veux la sortie comme ça,

yearAndMonth  =  [
    { "year": 2013, "month": "JANUARY " },
    { "year": 2013, "month": "FEBRUARY" },
    { "year": 2015, "month": "FEBRUARY" },
    { "year": 2015, "month": "MARCH" }
]

Comment y parvenir?

7
Aniket Avhad

Vous pouvez également utiliser la bibliothèque lodash pour trier les données en plusieurs colonnes.

J'ai créé une démo sur Stackblitz. J'espère que cela vous aidera/guidera les autres.

lodash - Documentation

Composant.html

<table width="100%">
  <tr>
    <td>Year</td>
    <td>Month</td>
  </tr>
  <tr *ngFor="let datas of sortedData">
    <td>{{datas.year}}</td>
    <td>{{datas.month}}</td>
  </tr>
</table>

Composant.ts

 sortedData: any[];
  data = [
    { "year": 2013, "month": "FEBRUARY" },
    { "year": 2015, "month": "MARCH" },
    { "year": 2013, "month": "JANUARY" },
    { "year": 2013, "month": "MARCH" },
    { "year": 2013, "month": "APRIL" },
    { "year": 2015, "month": "FEBRUARY" }
  ];

monthArray: any = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
        "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];

  ngOnInit() {
    this.sortedData = _.orderBy(data, [(datas) => datas.year, (user) => (this.monthArray.indexOf(user.month))], ["asc", "asc"]);
    console.log(this.sortedData);
  }
0
Krishna Rathore

Vous pouvez prendre un objet pour les noms de mois et leur valeur numérique.

La chaîne de la commande en prenant le delta de l'année et du mois.

var array =  [{ year: 2013, month: "FEBRUARY" }, { year: 2015, month: "MARCH" }, { year: 2013, month: "JANUARY" }, { year: 2015, month: "FEBRUARY" }];

array.sort(function (a, b) {
    var MONTH = { JANUARY: 0, FEBRUARY: 1, MARCH: 2, APRIL: 3, MAY: 4, JUNE: 5, JULY: 6, AUGUST: 7, SEPTEMBER: 8, OCTOBER: 9, NOVEMBER: 10, DECEMBER: 11 };
    return a.year - b.year || MONTH[a.month] - MONTH[b.month];
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

3
Nina Scholz

Vous pouvez créer une carte qui associe le mois au numéro de mois, puis utiliser Arrays.sort() avec votre propre comparateur personnalisé:

let months = { 'JANUARY' : 1, 'FEBRUARY' : 2, 'MARCH' : 3, 'APRIL' : 4, 'MAY' : 5, 'JUNE' : 6, 'JULY' : 7, 'AUGUST' : 8, 'SEPTEMBER' : 9, 'OCTOBER' : 10, 'NOVEMBER' : 11, 'DECEMBER' : 12 };
let  yearAndMonth  =  [ { "year": 2013, "month": "FEBRUARY" }, { "year": 2015, "month": "MARCH" }, { "year": 2013, "month": "JANUARY" }, { "year": 2015, "month": "FEBRUARY" } ];

yearAndMonth.sort((a,b)=> a.year - b.year || months[a.month.toUpperCase()] - months[b.month.toUpperCase()]);

console.log(yearAndMonth);

1
amrender singh

Vous pouvez créer un tableau pour les noms de mois et trier comme ceci:

let data = [
  { "year": 2013, "month": "FEBRUARY" }, { "year": 2015, "month": "MARCH" },
  { "year": 2013, "month": "JANUARY" }, { "year": 2015, "month": "FEBRUARY" }
];

let months = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
              "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];

data.sort(
 (a, b) => (a.year - b.year) || (months.indexOf(a.month) - months.indexOf(b.month))
);


console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1
Mohammad Usman

Déclarer les noms de mois dans un tableau pour obtenir la valeur relative de la chaîne de mois lors de la comparaison les uns avec les autres.

La première comparaison porte sur l'année, si les deux valeurs de l'année sont identiques, passez à la comparaison des mois en fonction du tableau de mois créé. 

let months = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
          "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];



yearAndMonth.sort((a,b) =>{
    if(a.year > b.year) return 1;
    else if(a.year <  b.year) return -1;
    else {
        if(months.indexOf(a.month.toUpperCase()) > 
           months.indexOf(b.month.toUpperCase()))
               return 1;
        else if(months.indexOf(a.month.toUpperCase()) < 
         months.indexOf(b.month.toUpperCase())) 
               return -1
        else return 0;
  }
});
0
Amardeep Bhowmick

Voir aussi: JsFiddle

Me permettre de fournir une version ES simple (trier un tableau d'objets sur une ou plusieurs valeurs de clé, dépendant de la série (trier sur 1, trier 2 dans 1, trier sur 3 dans 1 et 2, etc.), non mutant, c'est-à-dire garder l'original tableau tel quel):

const log = (...str) => 
  document.querySelector("pre").textContent += `${str.join("\n")}\n`;
const data = getData();
const xSort = XSort();
const months = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
    "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ];

log( JSON.stringify(
    xSort
    .create(data)
    .orderBy( {key: "year"}, { key: v => months.indexOf(v.month) } ),
    null,
    " ")
  );

function XSort() {
  const multiSorter = sortKeys => {
    if (!sortKeys || sortKeys[0].constructor !== Object) {
      throw new TypeError("Provide at least one {key: [keyname]} to sort on");
    }
    return function (val0, val1) {
      for (let sortKey of sortKeys) {
        const v0 = sortKey.key instanceof Function ? sortKey.key(val0) : val0[sortKey.key];
        const v1 = sortKey.key instanceof Function ? sortKey.key(val1) : val1[sortKey.key];
        const isString = v0.constructor === String || v1.constructor === String;
        const compare = sortKey.descending ?
          isString ? v1.toLowerCase().localeCompare(v0.toLowerCase()) : v1 - v0 :
          isString ? v0.toLowerCase().localeCompare(v1.toLowerCase()) : v0 - v1;
        if (compare !== 0) {
          return compare;
        }
      }
    };
  }
  const Sorter = function (array) {
    this.array = array;
  };

  Sorter.prototype = {
    orderBy: function(...sortOns) {
      return this.array.slice().sort(multiSorter(sortOns));
    },
  };

  return {
    create: array => new Sorter(array)
  };
}

function getData() {
  return [{
      "year": 2013,
      "month": "FEBRUARY",
    },
    {
      "year": 2015,
      "month": "MARCH",
    },
    {
      "year": 2015,
      "month": "SEPTEMBER",
    },
    {
      "year": 2013,
      "month": "JANUARY",
    },
    {
      "year": 2013,
      "month": "MARCH",
    },
    {
      "year": 2013,
      "month": "APRIL",
    },
    {
      "year": 2015,
      "month": "FEBRUARY",
    }
  ];
}
<pre></pre>

0
KooiInc