Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the years from an array of dates in order

I have this array:

var array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];

How can I get the years from it in order? So the result would be this:

result = ['2020','2021','2022'];

Do I have to change the array to a new Date() format and sort, or how would be the best way ? Any Suggestion ?

like image 675
NewProgrammer Avatar asked Sep 29 '21 11:09

NewProgrammer


2 Answers

Using a combination of ... , Set , .map() and .sort(). This can be done in one line.

... -> destructures array into individual items.

new Set() -> make a set out of the new items.

map() -> runs a loop and map the array into a new one.

split() -> breaks a string into array.

sort() -> sorts an array.

var array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];

console.log([...new Set(array1.map(x => x.split('/')[1]))].sort());
like image 153
Tushar Shahi Avatar answered Nov 01 '22 22:11

Tushar Shahi


simply you can use map method to iterate over your array and then get every element and split them or separate them using Regex.

const array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];

// separate each data into month and year and get the years in the result array
const result = array1.map(data => data.split("/")[1])

// make years uinque with this simple hack 
const uniqueResult = [...new Set(result)]

// now you can sort your the data 
const sortedUniqueResult = uniqueResult.sort((a, b) => a - b)

console.log(sortedUniqueResult)

You can also use javascript methods chaining to convert the above snippet into one line of code:

const array1 = ['9/2022','7/2020','11/2021','12/2020','2/2020','4/2021','10/2021'];

const result = [...new Set(array1.map(data => data.split("/")[1]).sort((a, b) => a - b))]
    
console.log(result)
like image 20
nima Avatar answered Nov 02 '22 00:11

nima