I have an array
I want to delete the price when it is = 0
Why when I want to delete the array whose price is 0 does not delete all array ?
Where is problem ?
var products = [{
specs: "name",
shopLink: "linamazon",
shopLogoUrl: "icon Store/Amazon22.png",
price: 0,
priceUpdate: "Amazon.com",
storeName: "Amazon"
},
{
specs: "name",
shopLink: "linknewegg",
shopLogoUrl: "icon Store/NewEgg.png",
price: 0,
priceUpdate: "NewEgg.com",
storeName: "NewEgg"
},
{
specs: "name",
shopLink: "linknoon",
shopLogoUrl: "icon Store/noon-logo2.png",
price: 0,
priceUpdate: "icon Store/Noon.com",
storeName: "Noon"
},
{
specs: "name",
shopLink: "linkebay",
shopLogoUrl: "icon Store/ebay33.png",
price: 0,
priceUpdate: "Ebay.com",
storeName: "Ebay"
},
];
for (i = 0; i < products.length; i++) {
if (products[i].price == 0) {
products.splice(i, 1)
}
}
console.log(products)
You're modifying the array in the middle of a loop. This causes the array to shrink, and so i is now referring to a different element. When i increments, you then end up skipping over a value. One possible fix is to change i at the same time you modify the array:
for (i = 0; i < products.length; i++) {
if (products[i].price == 0 ) {
products.splice(i, 1)
i -= 1; // <--------------- added
}
}
Or you can consider using another approach, such as the .filter method on arrays:
products = products.filter(product => product.price !== 0);
Try using something like :
const arr = products.filter(x => x.price > 0);
You can even add casting to Number();
The problem is what @epascarello and @d-m said in comments, removing them will change the index of items in the array, so your loop will miss a few of them.
And the standard answer is what @aayoub-el-aboussi said
But if you want to keep the for loop for better performance, you just have to reverse the loop, it means try to count from end to start. As the example:
for loopsvar products = [{
specs: "name",
shopLink: "linamazon",
shopLogoUrl: "icon Store/Amazon22.png",
price: 0,
priceUpdate: "Amazon.com",
storeName: "Amazon"
},
{
specs: "name",
shopLink: "linknewegg",
shopLogoUrl: "icon Store/NewEgg.png",
price: 0,
priceUpdate: "NewEgg.com",
storeName: "NewEgg"
},
{
specs: "name",
shopLink: "linknoon",
shopLogoUrl: "icon Store/noon-logo2.png",
price: 0,
priceUpdate: "icon Store/Noon.com",
storeName: "Noon"
},
{
specs: "name",
shopLink: "linkebay",
shopLogoUrl: "icon Store/ebay33.png",
price: 0,
priceUpdate: "Ebay.com",
storeName: "Ebay"
},
];
for (i = products.length-1; i >=0; i--) {
if (products[i].price == 0) {
products.splice(i, 1)
}
}
console.log(products)