Determine whether to push or update object in array based on unique ID I am trying to write a basic function that will decide whether the object already exists in array of objects based on unique id that is inside this object as a property. Upon searching I came up with this code, and it seems to be doing the job fine, but I can imagine there is a better and faster way to determine whether to push or update the object. If you could share your best answer for this please...

var myArray = [
  {
    id: 1,
    car: "Ford"
  },
  {
    id: 2,
    car: "Honda"
  }
];

var objToOverwrite = {
  id: 1,
  car: "Bentley" // to overwrite car: "Ford"
};

var objToPush = {
  id: 3,
  car: "Toyota"
};


function pushToArray ( arr, obj ) {


  var existingIds = arr.map((obj) =&gt; obj.id);

    if (! existingIds.includes(obj.id)) {
      arr.push(obj);
    } else {
      arr.forEach((element, index) =&gt; {
        if (element.id === obj.id) {
          arr[index] = obj;
        };
      });
    };
};

pushToArray ( myArray, objToPush );

console.log(myArray);
Your pushToArray function is less efficient than it could be because it it looping over the entire array multiple times. We could instead use find()/findIndex() to loop over the array just once:

function pushToArray(arr, obj) {
    const index = arr.findIndex((e) =&gt; e.id === obj.id);

    if (index === -1) {
        arr.push(obj);
    } else {
        arr[index] = obj;
    }
}


This is still O(n) performance, but does less repeated work and does not require altering the data structure you are using.

If you need better performance than that, you can keep the array sorted by ID and implement a simple binary search, or you can change your data structure to one more optimized for fast lookups.