In JavaScript, not all elements are removed in a single iteration, even if the condition is consistently met

I'm currently attempting to compare two arrays containing multiple objects and remove elements based on a condition. To my surprise, while testing in Chrome's console, I noticed that the first array (arr1) is not being emptied even though I am using an if condition that should always evaluate to true. After the initial iteration, there is always at least one object remaining, and it takes several loops for the element to finally be removed. Is there something obvious that I'm overlooking? It feels like such a fundamental JavaScript mistake.

var car1 = {
  type: 'das',
  model: '1',
  color: 'blue'
} //sample object
arr1 = []
for (i = 0; i < 5; i++) {
  arr1[i] = car1
} //filling object with values

for (i in arr1) {
  if (arr1[i].type == 'das') { //removing element with condition which always matches
    arr1.splice(i, 1);
  }
}
console.log(arr1);

Answer №1

It is crucial to avoid altering the value of an array within its loop.

var car1 = {
  type: 'das',
  model: '1',
  color: 'blue'
} //sample object
arr1 = []
for (i = 0; i < 5; i++) {
  arr1[i] = car1
} //filling object with values
arr2 = [];
for (i in arr1) {
  if (arr1[i].type != 'das') { //removing element with condition which always matches
    arr2.push(arr1[i]);
  }
}
arr1 = arr2
console.log(arr1);

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

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

What is causing the chat-widget to display a null value for the style read property?

Could someone assist me with hiding the Widget-chat? I keep getting an error that the property of style is null. Any help would be greatly appreciated. Thank you in advance. document.getElementById("chat-widget").style.display='none'; ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Simulating SOAP requests using the Nock library

I have a project in progress involving a node application that interacts with soap services. To handle parsing of JSON into a valid SOAP request and vice versa for the response, I am using the foam module. Everything works smoothly when communicating with ...

Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array: [ {"data": [ {"W":1,"A1":"123"}, {"W":1,"A1":"456"}, {"W":2,"A1":"4578"}, {"W":2,"A1":"2423"}, {"W":2,"A1":"2432"}, {"W":2,"A1":"24324" ...

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

Promise.all() ensures that all promises in the array are resolved with the same value

Currently, I'm in the process of developing a module that contains a function designed to return a promise using Promise.all() for the purpose of sending emails to multiple users. By simplifying the code, I have managed to isolate and reproduce the is ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Exploring the world of form interactions in Angular: A guide to creating dynamic element communication

I have created a form using Angular, and I want to display a specific value in my input field when an element is selected from the dropdown. Additionally, since the values in the dropdown are fetched from a server, I want to show a corresponding label for ...

I am encountering an issue where I am unable to successfully fetch a cookie from the Express backend to the React

const express = require("express"); // const storiesRouter = require("./routes/storiesRouter") // const postsRouter = require("./routes/postsRouter"); // const usersRouter = require("./routes/usersRouter"); const cors = require("cors"); const cookieParser ...

Do the dependencies in the devDependencies section impact the overall size of the

My search for a definitive answer to this question was fruitless. Are the packages I include as devDependencies included in the final production JS bundle, impacting its size? Or does only the dependencies list affect the bundle's content? ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Interactive form found on a webpage

Hey there! I'm currently working on a task where I want a form to be displayed when the edit button is clicked. Once the save button in the form is pressed, I want to update my database with the new information. It's crucial that this process hap ...

What is the best way to incorporate animation into a React state?

Looking to implement a fade-in animation for the next index but struggling with tutorials using "react transition group" that are focused on class components or redux. const AboutTestimonials = () => { const [index, setIndex] = useState<any>(0 ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Generating a component and rendering it according to the dynamic route parameters using mapStateToProps and reselect techniques

I have set up a global app container to store data for different rooms, with a sub-container called roomDetails that utilizes a reselect selector to pick a room from the global state based on ownProps.params.slug. This process is accomplished through mapSt ...

When the only source is available, the image undergoes a transformation

Is there a way to dynamically adjust the height of an image using JQuery or JavaScript, but only when the image source is not empty? Currently, I have an image element with a fixed height, and even when there is no source for it, Chrome still reserves sp ...

Flask Modal fails to function properly in the absence of table data

I'm currently troubleshooting an issue with my modal on a Flask web app that utilizes a SQLite database. When trying to add new rows to the table using some JavaScript code, everything works perfectly unless the table is empty. In that case, I am unab ...

What is preventing me from accessing session data using nuxtServerInit?

When attempting to retrieve sessions, I encounter an issue. Is everything set up correctly in the following main files: server, config? store/index.js export const actions = { nuxtServerInit ({ commit }, { req }) { console.log(req); } The console log ...

"Execution of the console.log statement occurs following the completion of the request handling

When I have a piece of middleware that responds if no token is found, why does the console.log line still run after the request is responded to? I always believed that the res.json call would "end" the middleware. Any insights on this behavior would be g ...