Remove objects from array - Two different approaches, two different results when consulting the length of each array
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.
Answer
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);
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM