"Incorporating splice in a for loop is causing issues and not functioning

I've been attempting to remove an item from an array, but for some reason, it's not working. Here's the code I'm using:

vm.Continue = function () {
    $scope.invalidList = [];
    if (vm.errorexsist === true) {
        var table = document.getElementById('errortabel');
        for (var r = 0, n = table.rows.length; r < n; r++) {
            if (r > 0) {
                $scope.invalidList.push({
                    Error: table.rows[r].cells[0].val,
                    FirstName: table.rows[r].cells[1].children[0].value,
                    Email: table.rows[r].cells[2].children[0].value,
                    PhoneNumber: table.rows[r].cells[3].children[0].value,
                    Location: table.rows[r].cells[4].children[0].value,
                    Department: table.rows[r].cells[5].children[0].value
                });
            }
        }
        var i = $scope.invalidList.length;
        while (i--) {
            if (IsEmailValid($scope.invalidList[i].Email) === true && IsPhoneNumValid($scope.invalidList[i].PhoneNumber) === true) {
                $scope.invalidList.splice(i, 1);
            }
        }  
    }
};

The issue with the above code is that it always removes the item at index zero, even when the condition in the if statement is not met.

Answer №1

It is important to note that using Array.splice will change the length of the array. This means that if you are iterating through the array and calling splice inside the loop, the index and length of the loop will not be accurate. To avoid this issue, consider iterating backwards through the array.

var i = $scope.invalidList.length;
while (i--) {
    if (IsEmailValid($scope.invalidList[i].Email) === true && IsPhoneNumValid($scope.invalidList[i].PhoneNumber) === true) {   
        $scope.invalidList.splice(i, 1);   
    }
}

If your goal is to filter out items from an array based on a condition, you may want to use Array.filter as it is specifically designed for this purpose:

$scope.invalidList = $scope.invalidList.filter(item => !IsEmailValid(item.Email) || !IsPhoneNumValid(item.PhoneNumber));

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

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

expanding the values associated with a key in python

Looking to make a change, adding the following: { "Category": "Fruit" } into this block: { "Category": "Vegetable" { resulting in: "Name": "Menu1", "Categories":[ { &q ...

Expanding the flexbox container to accommodate additional divs when they are added

I'm encountering an issue with a div not extending properly, causing two other divs to overlap. I've managed to position the divs correctly, but now I need the "100% all beef weenies" text to appear below the items. Any suggestions on how to achi ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

What is the reason for handlers not being able to work without passing parameters in React?

I recently made a discovery but I'm still puzzled about how it works. In the past, when creating React components, I used to follow this pattern: class App extends React.Component { state = { input: '' } onChangeHandler = event = ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

Utilizing a drop-down selection menu and a designated container to store chosen preferences

My form includes a select dropdown that displays available options (populated from a PHP database). Users can choose options from the list, which are then added to a box below to show all selected items. However, I am facing a challenge with the multiple s ...

Why am I unable to locate my personalized module?

I've encountered an issue with my npm module not being found in my sample script after publishing it. Here is the link to my module: https://www.npmjs.com/package/kong-hmac https://github.com/y-zono/kong-hmac-js Here's what I have tried: $ m ...

Complete Search with the press of Enter on the Auto Textbox

I have implemented an Ajax auto complete extender on a TextBox control. As the user begins typing, suggestive options are displayed below the input field based on data retrieved from a webservice call. When OnClientItemSelected="GetCode" is triggered, the ...

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...

Transferring items between different containers without using innerHTML

I've got an embedded <ul> within a (hidden) <aside id="idDetails">. How can I move the ul element from inside the aside and position it in a <div id="projectSide"> without using innerHTML? Any solutions in both plain JavaScript and j ...

The error occurred while attempting to save the file to disk: 'setHeader() requires both a name and a value to be set.'

I am working on enabling image file uploads to the Node.js server in a MEAN Stack application. Utilizing ng-file-upload for the client-side angular directive has been successful so far. However, I have encountered an issue when attempting to pass the image ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Array failing to populate with accurate information

During the loop, I am populating an array: for k in one two three; do array+=( "$k" ) done echo $k[0] # Expecting to print 'one', but prints 'one[0]' echo $k[1] # Expecting to print 'two', but prints 'one[1]' W ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

What could be the reason for the malfunctioning of the "subscribe" button?

Whenever the subscribe button is clicked, it should send an email to the "subscriptions" section of the database. Unfortunately, when I click the button, nothing seems to happen. My understanding of this is very limited and I can't seem to troubleshoo ...

What steps should I take to ensure that the array yields the correct output?

Why is my code not creating an array of [0, 1, 2] when I pass the number 3 as a parameter? const array = [0]; const increment = (num) => { if (num > 0) { increment(num - 1); array.push(num); } return; }; console.log(array); incremen ...

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

Capitalizing a specific letter in a string at a designated index

Looking for an efficient way to convert a specific letter in a string to uppercase? Let's explore different methods: Suppose we have the string: let str = "Dwightschrute"; One way to achieve this is by slicing the string and then updating the desir ...

Angular - ui-router states are not being detected

I'm currently working on a Spring and Angular JS web application project. The structure of the project is as follows:https://i.sstatic.net/xgB4o.png app.state.js (function() { 'use strict'; angular .module('ftnApp') .con ...