Arrange a collection of objects based on the value of a particular key

In my current dataset, I have an array of objects with 12 indexes, each containing 2 values. The keys 'months' and 'year' are included in each index. 'Months' is a sub-array, while 'year' is currently stored as a string but could easily be converted to an integer.

My goal is to sort this array of objects based on the value of the 'year' key

Currently, the 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 am attempting to sort this list from lowest to highest years. I initially tried using map, but couldn't get it to work correctly. Any advice on how to achieve this would be greatly appreciated. Thank you.

Answer №1

Here's a straightforward solution - just sort the array using the Array.prototype.sort function. Since the year values are strings, you'll need to parse them as integers before sorting. Give this a try:

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);

Answer №2

Give this code a shot:

let information = [
  {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 sortedData = information.sort((item1, item2) => item1.year - item2.year);
console.log(sortedData);

Answer №3

To utilize the Array.sort method, simply provide a compare function as an argument.

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

Adding different colors for a range of values in the Grey_CircularLinearGauge component of DOJO can be achieved by customizing the

I'm currently working with the dojo toolkit and I am looking to incorporate the Grey_CircularLinearGauge component into my project. Here is an example of how I want it to look: In addition, I also need to customize the colors based on specific value ...

Expanding Arrays in TypeScript for a particular type

There is a method to extend arrays for any type: declare global { interface Array<T> { remove(elem: T): Array<T>; } } if (!Array.prototype.remove) { Array.prototype.remove = function<T>(this: T[], elem: T): T[] { return thi ...

Loop through a JSON-formatted string

I am currently faced with the challenge of passing the MongoDB Query Result in String Format to a JSP Page using Ajax. While I am able to successfully retrieve the data, I am struggling with how to iterate over that data. Note : The JSON Structure has a D ...

The identical items combined into a single array

I have a specific data structure that I am struggling to manipulate in JavaScript. The goal is to merge objects with the same invoice_nr into one array, while keeping other objects in separate arrays. const result = [ { invoice_nr: 16, order_id: ...

Is it possible to obtain the className of a leaflet divIcon within the <style scoped> portion of a vue component?

If you're looking for a Vue 2 sample project, check out this link When working on the declaration of divIcon in LeafletTest.vue, here is an example: const cloudIcon = L.divIcon({ html: thecloud, className: 'my-custom-icons& ...

Weapons of Mass Destruction - receive markdown content

My application is utilizing a markdown editor from Google Code. $(document).ready(function () { var converter = Markdown.getSanitizingConverter(); var editor = new Markdown.Editor(converter); editor.run(); }); <div class="wmd-panel"> ...

JavaScript filename

This question may appear simple, but I believe the answer is not as straightforward. Here it goes: Should I keep the filename of jQuery as "jquery-1.3.2.min.js" for compatibility reasons, or should I rename it to jquery.js? In my opinion, it's best ...

Look up HTML div tags and showcase the findings on a separate webpage

I am looking to search through multiple HTML files from a different page. I want to find text within all the divs that have a specific id, and display those divs on the search results page if they contain the matched search term. Here is an example of how ...

The event handler onClick is unresponsive in the button element within a React component

Hey there, I'm new to React and I'm having an issue with a class-based component. Below is my component that I'm calling inside another React component. I just want the temp function to be called when onClick is triggered, but it's not ...

Using Javascript within HTML: A guide on when to utilize semi-colons and when to implement the return false statement

Exploring the use of JavaScript attributes within HTML elements: <input type="button" onclick="somceFunc()" /> <input type="button" onclick="somceFunc();" /> <input type="button" onclick="somceFunc(); return false;" /> Debating whether ...

Setting a default value in an arrow function

Currently, I am working on a section of code that renders a simple loading bar. const smallSpinner = document.getElementById('spinner-small').getContext('2d'); let pointToFill = 4.72; let cw = smallSpinner.canvas.width; //Returns canva ...

Tips for integrating the react-financial-charts library into your React and JavaScript project

While exploring the react-financial-charts library, I discovered that it is written in TypeScript (TS). Despite my lack of expertise in TypeScript, I am interested in using this library in my React+JS project due to its active contributions. However, I hav ...

Invoke the controller function programmatically through dynamically generated HTML

In my controller, there is a function named $scope.removePoster. Within the same controller, there is a table creation function that calls $scope.removePoster like so: for(var i=0; i < 6 && postersNum >= 0; i++){ ... table += '<t ...

Retrieve the initial item from my array $_POST['tableFields']

Can someone help me with getting the first element from my associative array $_POST['tableFields']? print_r($_POST['tableFields']); // The output is: ["id","usuario","apellido1","apellido2"," ...

sending array to controller using a button within the yii2 framework

When I render an array with double digits from the controller to the view page, only the first single digit value is displaying. views/view1.php <a class="btn btn-success" href="index.php?r=followusers/follow&id=<?= $follower1, $followed1; ?& ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

How can I maintain the hover color on a button with a text label even when hovering over the text label?

I need help creating a button with a text label that both respond to clicks and have a hover color. The current code I have works, but the hover color is lost when hovering over the text label. How can I modify the code to maintain the hover color even w ...

What is the best way to display data stored in local storage using React and Typescript?

Is there a way for the data to be displayed on the browser below the save button when I click save? My setup involves using React with a TypeScript template. function ButtonDefaultExample(props: IButtonExampleProps) { const { disabled, checked } = pro ...

A guide to implementing accurate pagination in Vue.js 2

I'm encountering an issue while setting up pagination with Vue. My goal is to load new tasks from jsonplaceholder when the numbers on the buttons are clicked. I have managed to successfully load the first and second pages. I believe this is directly ...