I create an array like this and remove one element:
var test = []
test.push({
bezeichnung: "test_1"
});
test.push({
bezeichnung: "test_2"
});
test.push({
bezeichnung: "test_3"
});
delete test[1]
But console.log(test.length) will show me "3", because my array shows an "empty slot" which will also count.
How can I fix this?
You can use .splice() to delete the data like this:
test.splice(1,1);
Then the test.length with show 2 as the array length.
If you do not wish to reindex the array, you can simply use the .filter() method to filter the undefined data from your array like this:
var test = []
test.push({
bezeichnung: "test_1"
});
test.push({
bezeichnung: "test_2"
});
test.push({
bezeichnung: "test_3"
});
delete test[1];
console.log(test.length) //will log 3
console.log(test.filter(a=>a).length) //will log 2
The last console statement in the above code snippet would filter the empty/undefined values from the array and show you the count.