Building a JavaScript Array Prototype Method


I am new to constructing a JavaScript Array prototype. Please only paste previous links that are directly appropriate as I have been sourcing on SO and on w3school.

I would like to create a method for an array that checks if the 'id' field within the object does not already exist in the array. If not, then 'push' object into the array, else do nothing.

Each object has a unique 'id' field.


var array = [{ id: 001, title: 'some title'},
               { id: 002, title: 'other title'}]

var object = {id: 001, title: 'some title'}

// if does not exist in array...
//else do nothing

I would like the function to take the 'id' field as an argument so this function has wider use.

Are there any drawbacks to extending the array.Prototype? Otherwise I can do a for loop instead to do the check without the prototype constructor.

Since your ids are integers you could just set that index in the array directly.

var array = [];
var object = {id: 001, title: 'some title'};
array[] = object;

That will overwrite the element in that location such that you won't get duplicates with the same id. Your js engine will automatically switch to using a sparse array rather than a contiguous array if your ids are far apart.