Sort array by month and year

sort array by value
sort an array
sort months in javascript
javascript sort date ascending and descending
sort array jquery
how to sort array alphabetically in javascript
javascript sort array of objects
angular sort array

I need help with sorting an array by month and year to display on chart respectively.

Array1: ['Mar19','Apr18','Jun18','Jul18','May18','Jan19'....];
Desired Output : [....'Apr18','May18','Jun18','Jul18','Jan19','Mar19'];

I also have another array with values for each month according to the array above respectively

Array2: ['Mar19_value','Apr18_value','Jun18_value','Jul18_value','May18_value'
       ,'Jan19_value'....];

Array2: ['55','2','3','0','21','132'....]; //real values

When the monthyear array sorts, I want the data in this array to move to a new position according to the monthyear position. Like this:

Desired Array1: [....'Apr18','May18','Jun18','Jul18','Jan19','Mar19'];
Desired Array2: [....'Apr18_value','May18_value','Jun18_value','Jul18_value','Jan19_value','Mar19_value'];

So I can pick the data later like this:

var label = array[4];
var value = array2[4];

How can this be accomplished?

You could get the date as a sortable string and sort it.

For getting more than one array sorted by one signature array, you could take sorting with map, where you sort an array of indices, indicating the final sorting and then reassign all arrays with this sorting.

The getD function returns a formatted string by taking an index of array0 for sorting. Inside of the function the string is destructed into month and year parts, and replaced by its ISO 8601 representation. The replacement function callback takes the matched items, returns an array with a formatted year and the month of an object with the month names and the related month numbers. Then, this array is joined and returned.

Sorting takes place with a comparison with String#localeCompare.

var array1 = ['Mar19', 'Apr18', 'Jun18', 'Jul18', 'May18', 'Jan19'],
    array2 = ['Mar19_value', 'Apr18_value', 'Jun18_value', 'Jul18_value', 'May18_value', 'Jan19_value'],
    array3 = ['55', '2', '3', '0', '21', '132'],
    indices = Object
        .keys(array1)
        .sort(function (a, b) {
            function getD(i) {
                var months = { Jan: '01', Feb: '02', Mar: '03', Apr: '04', May: '05', Jun: '06', Jul: '07', Aug: '08', Sep: '09', Oct: '10', Nov: '11', Dec: '12' },
                    s = array1[i];
                return s.replace(/^(...)(.+)$/, (_, m, y) => [y.padStart(4, '0'), months[m]].join('-'));
            }
            return getD(a).localeCompare(getD(b));
        }),
    result = [array1, array3].map(a => indices.map(i => a[i]));
  
result.forEach(a => console.log(...a));

Sort Month/Year array, Hello All, I've an array of month/year to sort var myArray = ['Oct/08', 'Jan/09', 'Mar/ 09', 'May/07', 'Apr/08', 'Dec/06']; I've an idea that declare a ha� Sorted dates are 3 12 1676 18 11 1982 25 3 2010 20 1 2014 19 4 2015 9 7 2015. Similarly in C, we can use qsort() function.. Related Problem: How to efficiently sort a big list dates in 20’s

You need change the string to new Date(dateString) format like

new Date(Month Date Year)

Updated regex Pattern for Both Array

https://regex101.com/r/h1cm1z/2/

Updated Sort Second array based on first array sorting index

var arr1 =  ['Mar19','Apr18','Jun18','Jul18','May18','Jan19'];
var arr2 =['55','2','3','0','21','132'];

function datesort(arr){
 return arr.concat().sort((a,b)=>{
 a = a.replace(/(\d+)(.*)/g,' 1 $1'); // Month 1 YEAR
 b = b.replace(/(\d+)(.*)/g,' 1 $1'); // Month 1 YEAR
  return new Date(a) - new Date(b)
})
}

var after_arr1 =new datesort(arr1);
var after_arr2 = arr1.reduce(function(a,b,c){
     var ind = after_arr1.indexOf(b);
     a[ind] = arr2[c]
     return a
},[]);


console.log(after_arr1.join(','));
console.log(after_arr2.join(','))

Sort an Object Array by Date in JavaScript, dateString: It represents a date format. year: It represents the integer values which ranges from years 1900 to 1999. month: It is represented by� Sort array by month and year - cfxtrjtrk.blogspot.com 6 3

To order properly you need to know the order of the months. This is not alphabetical so you can use an array with the order of the months then look them up.

const monthOrder = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

Is already properly sorted and can be used in conjunction with .indexOf() to get the position of a month.

const myArr =  ['Mar19','Apr18','Jun18','Jul18','May18','Jan19'];
const myArr2 = ['Mar19_value','Apr18_value','Jun18_value','Jul18_value','May18_value'
   ,'Jan19_value'];

const monthOrder = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

let sortYearMonth = (a, b) => {
    let monthA = monthOrder.indexOf(a.slice(0,3))
	let yearA = a.slice(3,6)
	let monthB = monthOrder.indexOf(b.slice(0,3))
	let yearB = b.slice(3,6)
	return (`${yearA}-${monthA}` < `${yearB}-${monthB}`) ? -1 : (`${yearA}-${monthA}` > `${yearB}-${monthB}`) ? 1 : 0
}

let sortedMonths = myArr.sort(sortYearMonth)
let sortedMonths2 = myArr2.sort(sortYearMonth)

console.log(sortedMonths )
console.log(sortedMonths2 )

Sort an array of string of dates in ascending order, Approach: Extract the days, months and years as sub-strings from the string then compare two strings by years, if years for two dates are equal� Inside of the fuinction the string is destructed into month and year parts and replaced by its ISO 8601 representation. The callback of the replacement function takes the matched items, retuns an array with a formatted year and the month of an object with the month names and the related month numbers. Then this array is joined and returned.

const input = ['Mar19', 'Apr18', 'Jun18', 'Jul18', 'May18', 'Jan19'];

//const output : ['Apr18','May18','Jun18','Jul18','Jan19','Mar19'];
//Can be done easily by using momentjs, darte-fns, but here i will do it natively

const t = {
  Jan: 1,
  Feb: 2,
  Mar: 3,
  Apr: 4,
  May: 5,
  Jun: 6,
  Jul: 7,
  Aug: 8,
  Sep: 9,
  Oct: 10,
  Nov: 11,
  Dec: 12
}
const giveConcatString = (a, t) => {
  const monthPart = a.substr(0, 3)
  const yearPart = a.substr(3)
  return `${yearPart}${t[monthPart]}`
}
const sortedArray = input.sort((a, b) => {
  const concatString = giveConcatString(a, t)
  const concatStringB = giveConcatString(b, t)
  return concatString <= concatStringB ? -1 : 1

})
console.log(sortedArray)

Javascript sorting arrays by date | by Avery Duffin, How many times do you need to sort an array? if you are wanting to compare dates more specifically then just by day, week, month and year. Sort list of data by month name with Sort function. To sort the data by month name from Jan to Dec, you should do as this: 1. Select the data range that you want to sort by month name, and click Data > Sort, in the Sort dialog box, do the following operations: (1.) Under the Column section, please select the column name that you want to sort

You can try this raw snippet.

var MY = ['Mar19', 'Apr18', 'Jun18', 'Jul18', 'May18', 'Jan19'];
var s = "JanFebMarAprMayJunJulAugSepOctNovDec";
// converting to raw date format
for (i in MY) {
  num = MY[i].match(/\d+/g);
  letr = MY[i].match(/[a-zA-Z]+/g);
  MY[i] = (s.indexOf(letr) / 3 + 1) + '-' + '20' + num;
}
// sorting logic
var sorted = MY.sort(function(a, b) {
  a = a.split("-");
  b = b.split("-")
  return new Date(a[1], a[0], 1) - new Date(b[1], b[0], 1)
});
// converting back to original array after sorting
res = [];
for (i in sorted) {
  var a = sorted[i].split('-');
  res[i] = (s.substr((parseInt(a[0]) - 1) * 3, 3)) + '-' + a[1].substr(2, 2);
}

console.log(res);

How to Sort an Array of Dates with JavaScript � GitHub, Finally, we are now able to call the sort method on our array of dates. // More info about array sorting: http://w3schools.com/jsref/jsref_sort.asp. // First let's sort the� And go to DATA tab, click Sort Smallest to Largest or Sort Largest to Smallest button under Sort & Filter group. The Sort Warning dialog will open. #4 select Enable the selection radio button, and click Sort button. You will see that the dates have been sorted by month only. And you can now delete the helper column. Sort Dates by Year

How to sort an array by date value in JavaScript, Find out how to sort an array of items by date value in JavaScript. I published more than 1000 blog posts in 3 years. I wrote all I learned on� Short Dynamic Solution: Here's a dynamic solution that does not require hard-coding an array of months: const month = f=>Array.from(Array(12),(e,i)=>new Date(25e8*++i

Sort array by year and month, Sort array by year and month. javascript sort date ascending and descending sort months in javascript sort an array lodash sort by date sort by timestamp� I have a Series object that has: date price dec 12 may 15 apr 13 .. Problem statement: I want to make it appear by month and compute the mean price for each month and present it with a sorted manner by month.

How to sort array of dates as stri…, The title is a little bit confusing, but I guess you want to sort an Array of date func parser(aDate: String) -> (y: Int, m: Int, d: Int) { var year = 0 var month = 0 var� Inside of the function the string is destructed into month and year parts, and replaced by its ISO 8601 representation. The replacement function callback takes the matched items, returns an array with a formatted year and the month of an object with the month names and the related month numbers. Then, this array is joined and returned.

Comments
  • What have you tried so far?
  • Are you sure the sorting is correct format? i think you are sorted MMDD Format its a MMYY
  • @prasanth, thank you for the hint. i thought, the number is a day.
  • if i only want to perform this with array 1 and array 3?
  • @AmirQureshi, then you need oly the wanted array in the array for getting a new sort. please see edit.
  • do you want to get new arrays?
  • Thank you , it works as required. What if i have another array with values for each month respectively according to the monthyear array. how do i sort it when the monthyear moves to a new position. do you understand what i am saying?
  • i could added the format of date .you could change your array value like this.If you have any new position .Kindly change regex pattern and reproduce the same date format.Or post your new position. i will give the matching pattern
  • Or where did you get this array? You could format array with in pattern on the place of array create.or with something added delimiters like MM_YY,YY-MM
  • I think you did'nt understand the updated question mate. the answer you gave to sort the array is working and its fine. but when i sort array1 i also need array2 sorted accordingly to array1 so i can fetch the info from arrays as show above
  • you need to sort array2 based on array1 sorted index position right?