How to remove uninitialized objects from an array

Benchmark created by Stan Omoregie on


Setup

var initId = 4,    
      removedObjects = [],
      description = '',
      objectArray = [{Id: 1, isObsolete: false, Name: "Yellow"},
                     {Id: 2, isObsolete: true, Name: "Green"},
                     {Id: 3, isObsolete: false, Name: "Blue"},
                     {Id: 4, isObsolete: true, Name: "Purple"},
                     {Id: 5, isObsolete: false, Name: "Black"}];
  
  function forEachLoopObjectRemoval(obj, sId) {
     var removedObjA = [];
     description = 'forEachLoopObjectRemoval: ';
     obj.forEach(function (sub, i) {
        if (sub.isObsolete === true && sub.Id !== sId) {
           removedObjA.push(sub);
           obj.splice(i, 1);
        }
     });
     return removedObjA;
  }
  
  function forLoopObjectRemoval(obj, sId) {
     var removedObjB = [];
     description = 'forLoopObjectRemoval: ';
     for (var j = 0; j < obj.length; j++) {
        if (obj[j].isObsolete === true && obj[j].Id !== sId){
           removedObjB.push(obj[j]);
           obj.splice(j, 1);
           j--;
        }
     }
     return removedObjB;
  }
  
  function whileLoopObjectRemoval(obj, sId) {
     var removedObjC = [];
     description = 'whileLoopObjectRemoval: ';
     var keys = Object.keys(obj), i = keys.length;
     while (i--) {
        if (obj[i].isObsolete === true && obj[i].Id !== sId) {
            removedObjC.push(obj[i]);
            obj.splice(i, 1);
        }
     }
     return removedObjC;
  }

Teardown



            //console.log(description, JSON.stringify(removedObjects));
        
  

Test runner

Ready to run.

Testing in
TestOps/sec
ForEach-Loop
removedObjects = forEachLoopObjectRemoval(objectArray, initId);
ready
For-Loop
removedObjects = forLoopObjectRemoval(objectArray, initId);
ready
While-Loop
removedObjects = whileLoopObjectRemoval(objectArray, initId)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Stan Omoregie on