JavaScript Create a nested object from a Javascript array

I have an array of object. Each item has a paret id mentioned. I want to create a nested object where it nesting goes on as much as the subcategories. Input and expected output given below. How can I achieve this with plain JS?

var inputArr = [
  {
    category_id: 1,
    parent_category_id: 3,
    title: "category1"
  },
  {
    category_id: 2,
    parent_category_id: 1,
    title: "category2"
  },
  {
    category_id: 3,
    title: "category3"
  },
  {
    category_id: 4,
    parent_category_id: 1,
    title: "category4"
  },
  {
    category_id: 5,
    parent_category_id: 2,
    title: "category5"
  }
]


var expectedOutput = {
  category_id: 3,
  title: "category3",
  subcategories: [
    {
      category_id: 1,
      subcategories: [
       {
         category_id: 2,
         title: "category2",
         subcategories: [
           {
             category_id: 5,
             title: "category5"
           }
         ]
       },
       {
         category_id: 4,
         title: "category4"
       }
      ]
    }
  ]
}
Answer:1

Consider the following: function filterFoods() { var foods = [ {food: 'Bacon'}, {food: 'Butter'}, {food: 'Chicken'}, {food: 'Cocoa butter'}, {food: 'Saussages'}, {food: 'Ham'}, {food: ...

Consider the following: function filterFoods() { var foods = [ {food: 'Bacon'}, {food: 'Butter'}, {food: 'Chicken'}, {food: 'Cocoa butter'}, {food: 'Saussages'}, {food: 'Ham'}, {food: ...

Iam trying to start my script after another script finished his work and returned rt():adv.bind to console. The script is running in an iframe. I tried it with window.addEventListener but the script ...

Iam trying to start my script after another script finished his work and returned rt():adv.bind to console. The script is running in an iframe. I tried it with window.addEventListener but the script ...

I am working on a piece of legacy code for a table. In certain cells, I'm adding a notice icon. When you hover over the icon a <span> is made visible displaying some information. I would like to ...

I am working on a piece of legacy code for a table. In certain cells, I'm adding a notice icon. When you hover over the icon a <span> is made visible displaying some information. I would like to ...

I have a lot of files that I need to upload to my database, I am doing this through the browser and the server is having sizing issues with the data that is being sent to it and it rejects it. The ...

I have a lot of files that I need to upload to my database, I am doing this through the browser and the server is having sizing issues with the data that is being sent to it and it rejects it. The ...