Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How i can do bubble sort to array with object?

There is a task to make array sorting through Bubble sort. I just can’t understand how exactly it is necessary to implement sorting of such an array, in which objects. Can someone helpme, pls. I need sorting by data.year.

 const [table, setTable] = useState([
{
  text: 'Пошел в свой первый класс',
  id: 0,
  data: {
    year: 2012,
    day: 25,
    month: 1,
  },
},
{
  text: 'Поехал на чемпионат по бейсболу',
  id: 1,
  data: {
    year: 2018,
    day: 14,
    month: 3
  }
},
{
  text: 'Поступил в институт',
  id: 2,
  data: {
    year: 2007,
    day: 12,
    month: 4
  },
},

]
)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This will return the sorted array

function bblSort(arr) {
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr.length - i - 1; j++) {
      if (arr[j].data.year > arr[j + 1].data.year) {
        var temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return(arr);
}


var arr = [
  {
    text: "Пошел в свой первый класс",
    id: 0,
    data: {
      year: 2012,
      day: 25,
      month: 1,
    },
  },
  {
    text: "Поехал на чемпионат по бейсболу",
    id: 1,
    data: {
      year: 2018,
      day: 14,
      month: 3,
    },
  },
  {
    text: "Поступил в институт",
    id: 2,
    data: {
      year: 2007,
      day: 12,
      month: 4,
    },
  },
];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading