I am working on a cesium-react project to add common functionalities on the cesium-map using react. This is my Source Code.
create bug
download the code from link above and run the app and go to http://localhost:3000/map
select Add markers from Drop Down and click on button enable-drop-marker then click few places on the map left clicks after that press clear All button.
With the press of this button it should remove all the markers from the map which are named as marker.
Issue
when ever I use this line map.entities.remove(entityArray[i]);my the loop will run
length-of-array / 2.
times. I have used .map menthod and simple for loop and printed values of i and value at each index. I am stuck here. even chatGTP is confused with this bug. please guys help me…
Issue is in this part in the map.jsx component
useEffect(() => {
// console.log("button Cliked 00 : ", BtnClearAll);
// console.log("markerArrays : 11 ", markerArrays);
if (BtnClearAll) {
let map = mapRef.current;
//let item = map.entity.indexAt(0);
console.log("map. entity : ", map.entities);
let entityArray = map.entities._entities._array;
if (markerArrays.length > 0) {
console.log("Entity length is : ", entityArray.length);
entityArray.map((item) => {
console.log(item.name);
if (item.name === "marker") {
map.entities.remove(item);
}
});
// for (let i = 0; i < entityArray.length; i++) {
// console.log("ENtity name is " + i + " : ", entityArray[i].name);
// if (entityArray[i].name === "marker") {
// console.log("happy : ", i);
// map.entities.remove(entityArray[i]);
// }
// }
}
// handleClearMarkerArray();
}
dispatch(clearMarkerBtnClicked(false));
// let map = mapRef.current;
// map.entities.removeAll();
}, [BtnClearAll]);
>Solution :
The issue is caused by modifying the entityArray while iterating over it. When you remove an item from the array, the indices of the remaining items change, causing the loop to skip some elements. To fix this, you can iterate over a copy of the array or remove elements in reverse order.
Here’s a solution using a reverse loop:
if (markerArrays.length > 0) {
console.log("Entity length is : ", entityArray.length);
for (let i = entityArray.length - 1; i >= 0; i--) {
console.log("ENtity name is " + i + " : ", entityArray[i].name);
if (entityArray[i].name === "marker") {
console.log("happy : ", i);
map.entities.remove(entityArray[i]);
}
}
}
This will ensure that you are not modifying the indices of the remaining items in the array while iterating.