Q:

javascript return array of nested object and arrange similar types

javascript return array of nested object and arrange similar types
I have objects
let obj1 = { categoryId:1, category:"Fruits", name:"Orange"}
let obj2 = { categoryId:1, category:"Fruits",name:"Apple"}
let obj3 = { categoryId:2, category:"Vegetables", name:"Onion"} 
let obj4 = { categoryId:2, category:"Vegetables", name:"Ginger"}....etc

I want to create a array of nested object from this array expected:
let result =   

 [
         {
          name: "Fruits", values: [
            {
            "categoryId": 1,
            "category": "Fruits",
            "name": "Orange"
            }, 
            {
            "categoryId": 1,
            "category": "Fruits",
            "name": "Apple"
          }
         ]
        },
         { name:"Vegetables", values: [
            {
            "categoryId": 2,
            "category": "Vegetables",
            "name": "Onion"
            }, 
            {
            "categoryId": 2,
            "category": "Vegetables",
            "name": "Ginger"
          }
         ]
        }
    ]

I am looking for a function to add to the map one by one not all at once
addtoArray( obj1);
addtoArray( obj2); 
addtoArray( obj3); 
addtoArray( obj4);....etc 

Also a remove function:
removeFromArray( obj1);

In delete the object must not be same: 
{ categoryId:1, category:"Fruits", name:"Orange", newItem:"newvalue"}

It should be deleted using category:"Fruits" reference
Deleting an object, until no more objects are in the group. Then the group gets removed as well.
What I tried is below
function addtoArray(collection, object) {
    if (!collection[object.category]) {
        collection[object.category] = [object];
        return;
    }
    if (collection[object.category].includes(object)) return;
    collection[object.category].push(object);
}

function removeFromArray(collection, object) {
    if (!collection[object.category]) return;
    var index = collection[object.category].indexOf(object);
    if (index === -1) return;
    collection[object.category].splice(index, 1);
    if (!collection[object.category].length) delete 
    collection[object.category];
}

var obj1 = { categoryId: 1, category: "Fruits", name:"Orange" },
    obj2 = { categoryId: 1, category: "Fruits", name:"Apple" },
    obj3 = { categoryId: 2, category: "Vegetables", name:"Onion" },
    obj4 = { categoryId: 2, category: "Vegetables", name:"Ginger" },
    collection = {};

Please guide me!!

A:

Function for adding to the array:
var arr=[];

const addToArray=(arr,obj)=>{
  const index=findByName(arr,obj.category);
  if(index>-1){
    arr[i].values.push(obj)
  }else{
    arr.push({
      name:obj.category,
      values:[obj]
    })
  }
}
const findByName=(arr,name)=>{
  for(var i=0;i<arr.length;i++){
    if(arr[i].name===name)
      return i;
  }
  return -1;
}

addToArray(arr,obj1)

