Having difficulty deleting items with Three.JS

I'm currently using Three.JS to create a plane and add some boxes on top of it. I occasionally need to remove all the boxes. To achieve this, I have attempted using the code snippet below:

for (i = 0; i < scene.children.length; i++) {
    var object = scene.children[i];
    if (object != plane && object != camera) {
        scene.remove(object);
    }
}

/This code eliminates every object that is not the plane or the camera ;-)/

While it successfully removes some boxes, it fails to delete all of them =( Any suggestions on how to delete all boxes? Regards, José

Answer №1

It is important to remember to remove array objects from back to front rather than front to back.

var obj, i;
for ( i = scene.children.length - 1; i >= 0 ; i -- ) {
    obj = scene.children[ i ];
    if (obj !== plane && obj !== camera) {
        scene.remove(obj);
    }
}

The reason for this is because when you remove a node, the remaining nodes shift up in index numbers. For example, removing scene.children[0] will cause children[1] to become the new 0, and so on. By starting from the end of the array, you avoid skipping over any nodes during removal.

Additionally, this method may result in slightly faster performance, especially with larger arrays, as scene.children.length is only retrieved once at the beginning of the loop, rather than during each iteration.

Answer №2

@Crazycatz provided the correct answer, although it was given in 2016. Instead of manually iterating through the array, we can now simply use the .slice() method to create a copy of the array and iterate over it:

scene.children.slice().forEach(obj => scene.remove(obj))

If you prefer not to use ES6 features, you can achieve the same result like this:

scene.children.slice().forEach(function(obj) { scene.remove(obj); })

Answer №3

Consider utilizing !== instead of != for improved efficiency. Have you attempted to iterate through your loop and inspect the scene's children afterwards? It's possible that you may have inadvertently added some boxes to the plane as child elements, which are not being removed by this loop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert Screen Coordinates to World Coordinates with ThreeJS

While many people are interested in converting camera position to screen position, my question is how to achieve the opposite. Currently, I am trying to set the position of the "door" as a percentage of the screen, with the necessary calculations already ...

Generate an array using hyperlinks within a list item created by the user

In the process of developing a program, I have included a feature where users can drag and drop .wav files into a playlist-container. These files are then played in the order they are arranged within the playlist-container. Currently, I am working on imple ...

Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo https://i.stack.imgur.com/Yt4ya.png Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Mater ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

Include the particules.js library in an Angular 4 project

I am currently working on integrating Particles.js into my Angular project, but I am facing an issue with the Json file not loading. import { Component, OnInit } from '@angular/core'; import Typed from 'typed.js'; declare var particl ...

Finding tool for locating object names in JSON

JSON data: [ { "destination": "Hawaii", "Country": "U.S.A", "description": "...and so forth", "images": { "image": [ "hawaii1.jpg", "hawaii2.jpg", ...

Setting up Npm Sequelize Package Installation

Could use some help with setting up Sequelize. Here's the current status: https://i.sstatic.net/MQH1I.jpg ...

Modify the location of the input using jQuery

Hey there, I've got this snippet of HTML code: <div class='moves'> <div class='element'><input type='text' value='55' /></div> <input class='top' type='text&apo ...

The term 'Buffer' is not recognized in the context of react-native

Having trouble using buffer in my react-native app (developed with the expo tool). I have a hex value representing a geography Point like this for example -> 0101000020E61000003868AF3E1E0A494046B3B27DC8F73640 and I'm attempting to decode it into l ...

What is the best way to ensure that two objects collide with one another?

Issue Description I am currently working on implementing collision detection for two objects. The goal is to determine if the objects are intersecting by calculating their bounding boxes with Box3 and using the .intersectsBox() function to obtain a boolea ...

What methods can I use to ensure that a user's credentials are not shown in the URL?

My NextJS application sometimes behaves unexpectedly. Whenever I have a slow connection and the initial load time of the site is longer than usual, after trying to log in to the application, the credentials I entered are displayed in the URL. This happens ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...

React JS: How to prevent Yup and Formik error messages from being displayed multiple times upon submission

I have implemented Yup and Formik in my Sign up form to handle validation. My goal is to display specific errors based on the Yup validation rules I've set up. Take a look at the code snippet below: import React from 'react'; import { ...

Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the requ ...

When working with Three.js and Jest, a TypeError is thrown stating that 'getShaderPrecisionFormat' property cannot be read from undefined object

I am still learning about all the technologies involved in this project, so please be patient with me Building off of this previous question: Unit testing a ThreeJS application with Jest Having implemented the solution provided in the answer, I have crea ...

Building a dynamic map with React components using an array

Using the passed ID, a new element is dynamically generated: const Icon: FC<IconPropsI> = ({iconId, ...rest}) => { const iconsMap: IconsMapT = { IconUser: IconUser, IconTime: IconTime, IconVideo: IconVideo } return createElement ...

When passing req.body to another file for processing, it is displaying as undefined in node.js

Currently tackling an issue with a project involving nodejs where the request body is showing up as undefined Fetching some data on the client side, but encountering difficulties Received an error pointing out that the property is either undefined or nul ...

Issue with Jquery modal not functioning properly on second attempt

Currently, I am working on developing an application using CodeIgniter. However, I have encountered a problem where the modal window does not open for the second time. Here is a more detailed explanation of the issue: The form (view) in question contains ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

Typescript struggles to comprehend the nullish-coalescing operator

Within my Vue + TypeScript application, I've incorporated an external package called @moj/pagination-layout. This package utilizes the nullish operator internally. However, when attempting to run the build process, it encounters a failure and presents ...