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
  },
},

]
)

>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,
    },
  },
];

Leave a Reply