I currently have a set of data that contains an array of objects which have 12 indexs, and 2 values each.
Each one of the index contains the keys 'months' and 'year'. Months is a sub-array, and year is a string value (could easily be made a int).
I'm looking to sort my array of objects by the value of the year key
. For instance, currently, my data looks like this
0: {months: {…}, year: "2017"}
1: {months: {…}, year: "2019"}
2: {months: {…}, year: "2018"}
3: {months: {…}, year: "2011"}
4: {months: {…}, year: "2010"}
5: {months: {…}, year: "2012"}
6: {months: {…}, year: "2013"}
7: {months: {…}, year: "2015"}
8: {months: {…}, year: "2014"}
9: {months: {…}, year: "2016"}
I'm trying to sort this from years lowest -> highest. I tried using map, but I couldn't figure out the correct function. Any advice would be great, thank you.
CodePudding user response:
This is pretty simple. Sort the array using the Array.prototype.sort
function. As the year
is a string value so you have to parse it as an integer for sorting. Try this-
const data = [
{ months: null, year: "2017" },
{ months: null, year: "2019" },
{ months: null, year: "2018" },
{ months: null, year: "2011" },
{ months: null, year: "2010" },
{ months: null, year: "2012" },
{ months: null, year: "2013" },
{ months: null, year: "2015" },
{ months: null, year: "2014" },
{ months: null, year: "2016" },
];
data.sort((a, b) => parseInt(a.year) - parseInt(b.year));
console.log(data);
CodePudding user response:
Try this:
let data = [
{months: {a: 'a'}, year: "2017"},
{months: {a: 'a'}, year: "2019"},
{months: {a: 'a'}, year: "2018"},
{months: {a: 'a'}, year: "2011"},
{months: {a: 'a'}, year: "2010"},
{months: {a: 'a'}, year: "2012"},
{months: {a: 'a'}, year: "2013"},
{months: {a: 'a'}, year: "2015"},
{months: {a: 'a'}, year: "2014"},
{months: {a: 'a'}, year: "2016"}
];
let sorted = data.sort((a, b) => a.year - b.year);
console.log(sorted);
CodePudding user response:
Using Array.sort pass compare function to it.
const arr = [{months:[],year:"2017"},{months:[],year:"2019"},{months:[],year:"2018"},{months:[],year:"2011"},{months:[],year:"2010"},{months:[],year:"2012"},{months:[],year:"2016"},];
const res = arr.sort((a, b) => a.year - b.year);
console.log(res);