Remove items from array with splice in for loop
Solution 1
You can loop backwards, with something like the following:
var searchInput, i;
searchInput = ["this", "is", "a", "test"];
i = searchInput.length;
while (i--) {
if (searchInput[i].length < 4) {
searchInput.splice(i, 1);
}
}
DEMO: http://jsfiddle.net/KXMeR/
This is because iterating incrementally through the array, when you splice it, the array is modified in place, so the items are "shifted" and you end up skipping the iteration of some. Looping backwards (with a while
or even a for
loop) fixes this because you're not looping in the direction you're splicing.
Solution 2
At the same time, it's usually faster to generate a new array instead of modifying one in place. Here's an example:
var searchInput, newSearchInput, i, j, cur;
searchInput = ["this", "is", "a", "test"];
newSearchInput = [];
for (i = 0, j = searchInput.length; i < j; i++) {
cur = searchInput[i];
if (cur.length > 3) {
newSearchInput.push(cur);
}
}
where newSearchInput
will only contain valid length items, and you still have the original items in searchInput
.
DEMO: http://jsfiddle.net/RYAx2/
Solution 3
In addition to the second solution above, a similar, newer Array.prototype
method is available to handle that better: filter
. Here's an example:
var searchInput, newSearchInput;
searchInput = ["this", "is", "a", "test"];
newSearchInput = searchInput.filter(function (value, index, array) {
return (value.length > 3);
});
DEMO: http://jsfiddle.net/qky7D/
References:
Array.prototype.filter
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filterArray.prototype.filter
browser support - http://kangax.github.io/es5-compat-table/#Array.prototype.filter
Looping through array and removing items, without breaking for loop
The array is being re-indexed when you do a .splice()
, which means you'll skip over an index when one is removed, and your cached .length
is obsolete.
To fix it, you'd either need to decrement i
after a .splice()
, or simply iterate in reverse...
var i = Auction.auctions.length
while (i--) {
...
if (...) {
Auction.auctions.splice(i, 1);
}
}
This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.
Remove array item using for...of loop
You can't reasonably use for-of
for this. If you remove the "current" entry during the iteration, you'll skip the next entry, because of the way array iterators are specified (they use the index of the entry). You can see that with this contrived example:
const array = [1, 2, 3];for (const entry of array) { console.log(entry); if (entry === 2) { array.splice(1, 1); }}console.log(array);
Unable to remove items using splice within for loop in Angular
The problem is you are removing items from an array in cartService, but for the UI you are using values from the products array.
A quick fix is to reload your products array. Just add the following code in your removeProductFromCart
function in ShoppingCartComponent
. Add it at the end of the function.
this._cartService.getAddedProducts().subscribe((data: IProduct[]) => {
this.products = data.map(item => item[0]);
});
Apart from that there is another issue. You are hiding items in ShoppingCartComponent
html using *ngIf="removeItemId !== product.id"
. Consider you have three products (with id 1,2 and 3) in your cart, when the first products is removed, removeItemId
will have 1, so the first product will be hidden. But when the user removes the second product, removeItemId
will be set to 2, and now product one will be visible.
Is it supposed to be safe to remove elements from an array while iterating with for..of in JavaScript?
No, (as your example demonstrates) it's not safe to remove elements from an array while iterating it.
The default array iterator stores the current index, and it does not update this index when you call splice
on the array. It just continues at the same position, no matter what you did to the elements in the array. You can read the spec for ArrayIterator
objects, they basically work like a for (var index=0; index<array.length; index++) yield array[index];
loop.
.splice() removes item from two arrays - delete duplicates from array
The second array is the same object as the original array. To copy the array, you need to create a new array, and append the new array with the items from the first array.Below we use the spread operator to fill a new array with all the values from the main array.
let MainArray = [{
"name": "banana",
"lat": 3,
"lng": 3
},
{
"name": "apple",
"lat": 3,
"lng": 3
},
{
"name": "car",
"lat": 1,
"lng": 1
},
{
"name": "bike",
"lat": 1,
"lng": 1
}
];
let ArrayCopy = [...MainArray];
console.log(MainArray.length);
console.log(ArrayCopy.length);
for (let i = 0; i < MainArray.length; i++) {
for (let x = 0; x < ArrayCopy.length; x++) {
if ((MainArray[i].name !== ArrayCopy[x].name) && ((MainArray[i].lat === ArrayCopy[x].lat) || (MainArray[i].lng === ArrayCopy[x].lng))) {
//some output
ArrayCopy.splice(x, 1);
}
}
}
console.log(MainArray.length);
console.log(ArrayCopy.length);
How to iterate over an array and remove elements in JavaScript
Start from the top!
var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = elements.length - 1; i >= 0; i--){
if(elements[i] == 5){
elements.splice(i, 1);
}
}
Remove items from array with splice in for loop
Solution 1
You can loop backwards, with something like the following:
var searchInput, i;
searchInput = ["this", "is", "a", "test"];
i = searchInput.length;
while (i--) {
if (searchInput[i].length < 4) {
searchInput.splice(i, 1);
}
}
DEMO: http://jsfiddle.net/KXMeR/
This is because iterating incrementally through the array, when you splice it, the array is modified in place, so the items are "shifted" and you end up skipping the iteration of some. Looping backwards (with a while
or even a for
loop) fixes this because you're not looping in the direction you're splicing.
Solution 2
At the same time, it's usually faster to generate a new array instead of modifying one in place. Here's an example:
var searchInput, newSearchInput, i, j, cur;
searchInput = ["this", "is", "a", "test"];
newSearchInput = [];
for (i = 0, j = searchInput.length; i < j; i++) {
cur = searchInput[i];
if (cur.length > 3) {
newSearchInput.push(cur);
}
}
where newSearchInput
will only contain valid length items, and you still have the original items in searchInput
.
DEMO: http://jsfiddle.net/RYAx2/
Solution 3
In addition to the second solution above, a similar, newer Array.prototype
method is available to handle that better: filter
. Here's an example:
var searchInput, newSearchInput;
searchInput = ["this", "is", "a", "test"];
newSearchInput = searchInput.filter(function (value, index, array) {
return (value.length > 3);
});
DEMO: http://jsfiddle.net/qky7D/
References:
Array.prototype.filter
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filterArray.prototype.filter
browser support - http://kangax.github.io/es5-compat-table/#Array.prototype.filter
How to remove multiple specific elements from an Array using a loop in JavaScript?
Your error is probably because you splice elements inside loop, so if you console log the task, not every will be in output.
I found an solution, without foreach:
taskArr = [some DOM Elements]
const length = taskArr.length;
var deleted = 0;
for(var i = 0; i < length; i ++){
if(taskArr[i - deleted].children[1].className.includes("checked-Item")){
taskArr.splice(i - deleted, 1);
deleted ++;
}
}
Related Topics
Can Es6 Template Literals Be Substituted at Runtime (Or Reused)
Javascript: Which Browsers Support Parsing of Iso-8601 Date String with Date.Parse
How to Use Redirect in Version 5 of React-Router-Dom of Reactjs
Variable Scope in D3 JavaScript
Download and Open PDF File Using Ajax
JavaScript Drag and Drop for Touch Devices
How to Add Extra Info to Copied Web Text
Using Jquery to Replace One Tag with Another
Call a Function After Previous Function Is Complete
How to Convert Date to Timestamp
What Is the Correct Term for Variable Shadowing in JavaScript
My Very Simple Greasemonkey Script Is Not Running
How to Find First Element of Array Matching a Boolean Condition in JavaScript