0

I know I can make an algorithm which will sort the array i have but i want to know the best and most optimized way

This is the array i have now i want to sort it according to year so that the values with year 2021 will come first then 2022 and so on after that is done then i want to sort with respect to months so that the final array is like

[
 0: {month:'Aug', year:2021},
 1: {month:'Jul', year:2022},
 2: {month:'May', year:2100},
]

Reference object

Also my array length will never exceed 12

Sulman Azhar
  • 977
  • 1
  • 9
  • 26
  • This is probably something you're looking for: [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). You'll need to write your own comparing function, which shouldn't be that hard. – Bronislav Růžička Apr 27 '21 at 09:51

2 Answers2

1

const arr = [
  { month: "Aug", year: 2021 },
  { month: "Jul", year: 2022 },
  { month: "May", year: 2100 },
];

const months = {
  Jan: 1,
  Feb: 2,
  Mar: 3,
  Apr: 4,
  May: 5,
  Jun: 6,
  Jul: 7,
  Aug: 8,
  Sep: 9,
  Oct: 10,
  Nov: 11,
  Dev: 12,
};

arr.sort((a, b) => {
  if (a.year < b.year) return -1;
  else if (a.year === b.year) {
    return months[a.month] - months[b.month];
  } else return 1;
});

console.log(arr);

can also simplified as

arr.sort((a, b) => {
  if (a.year === b.year) {
    return months[a.month] - months[b.month];
  } else return a.month - b.month;
});

Thanks to georg for this concise suggestion(I personally like this conciseness)

const arr = [
  { month: "Aug", year: 2021 },
  { month: "Jul", year: 2022 },
  { month: "May", year: 2100 },
];

const months = {
  Jan: 1,
  Feb: 2,
  Mar: 3,
  Apr: 4,
  May: 5,
  Jun: 6,
  Jul: 7,
  Aug: 8,
  Sep: 9,
  Oct: 10,
  Nov: 11,
  Dev: 12,
};

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

console.log(arr);
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

You can use the function Array.prototype.sort() which takes a comparaison function as an argument:

const months = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
];

const array = [
  { month: "Aug", year: 2021 },
  { month: "Jul", year: 2022 },
  { month: "May", year: 2100 },
  { month: "Jan", year: 2100 },
];

console.log(
  array.sort((item1, item2) =>
    item1.year === item2.year
      ? months.indexOf(item1.month) - months.indexOf(item2.month)
      : item1.year - item2.year
  )
);
Poney
  • 471
  • 4
  • 10