Samantha J Samantha J - 2 years ago 54
Javascript Question

Is there another way to remove an element from an array without a for loop?

I am using this code:

self.contents.forEach(function (elem, index) {
if (elem['contentId'] === self.content.contentId)
self.contents.splice(index, 1);

With new browser capabilities, is there an easier way to remove the object from
that has a

Note that there is only ever one object in the contents array that has that Id

Answer Source

You can store your elements to an object with keys as their ID, then retrieve them by indexing on that:

//Procedure to add in the object, modify to meet your needs.
var storeObject = {};
storeObject[1] = elemWithID1;
storeObject[5] = elemWithID5;

Then, you can do:

elem = storeObject[self.content.contentId];

Considering that you practically use hash tables in that case, this mapping will have a probably average O(1) complexity than just by iteration search which will have O(n), which is better (consider it faster).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download