Remove objects from array - Two different approaches, two different results when consulting the length of each array

- 1 answer

Ad

I have two identical arrays: itemsOutput& itemsOutput2

I want to delete those objects in the arrays with attributes.type = "DIMENSION". I have found two different methods for doing so:

Method 1

jQuery.each(itemsOutput, function(i, val) {
    if(val.attributes.type == "DIMENSION") // delete index
      {
        delete itemsOutput[i];
      }
});
console.log(itemsOutput.length);

Method 2

metrics = itemsOutput2.filter(function (el) {
            return el.attributes.type === "METRIC";
          });
console.log(metrics.length);

Although both new arrays seem to have the same number of objects (and in both, all objects with attributes.type = "DIMENSION" are gone), the console shows two totally different values for the length of each array.

Method 1 removes the objects, but length is the same as the original array (although exploring the array in the console I observe that the objects keep their original indexes)

Method 2 not only removes the objects, but it also reassings the indexes successively. And for me, the code seems more clear, so I will stay with this method.

My question is, however, why this happens and if there could be problems if I use the results of method 1 in a loop, for example.

Ad

Answer

Ad

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array. When the delete operator removes an array element, that element is no longer in the array but the length stays the same.

You will need to use method splice if you want to remove it from the array. For example:

itemsOutput.splice(i, 1);
Ad
source: stackoverflow.com
Ad