maria maria - 1 year ago 119
Javascript Question

Javascript delete array result is leaving a comma

Im trying to remove a entery from the array, but after the loop, it leaves an comma seperator where the removed result is.

Q: How can i remove the comma from the array?

wanted output:

after loop

[{ number: 10, count: 1 }, { number: 5, count: 1 } ]

My current code:

console.log("before loop:");

for(var key in bNumbersCount) {
var card = bNumbersCount[key];
if (card['count'] != x) {
delete bNumbersCount[key];

console.log("after loop");

console log result:

before loop:
[ { number: 2, count: 3 },
{ number: 10, count: 1 },
{ number: 5, count: 1 } ]
after loop
[ , { number: 10, count: 1 }, { number: 5, count: 1 } ]

Answer Source

This isn't how you work with arrays in JavaScript.

  1. Don't use for-in on a JavaScript array unless you know what you're doing and have a specific reason; instead, use any of the several other ways outlined in this answer.

  2. Don't use delete on an array entry unless you know what you're doing and want to create a sparse array.

You probably wanted to loop through the array and actually remove entries. Two ways to do that:

  1. Create a new array with only the entries you don't want to remove, via filter:

    aNumbersCount = aNumbersCount.filter(function(entry) {
        return card.count == x;
  2. Use splice to modify your existing array in place, in which case you'll probably want to loop backward so the array indexes don't change on you:

    for (var n = aNumbersCount.length - 1; n >= 0; --n) {
        if (aNumbersCount[n].count != x) {
            aNumbersCount.splice(n, 1); // Removes one entry at index n

Side note: card['count'] can more simply be written card.count. You only need brackets notation and a string when the name of the property comes from an expression (such as getting a value from a variable) or if the name contains characters that make it an invalid IdentifierName (such as spaces).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download