1

Trying to delete elements from object using delete , but while the value is gone, there's still "empty" in the object. as show in the image:

enter image description here

which causing unwanted behviour in a following iteration:

for (const [key, value] of ids.entries()) {
    if (Object.values(this.widget_ids).indexOf(value) >= 0) {
        delete ids[key]
    }
}

now, i can't use pop or shift since . i need the option to remove by key, any idea how can i delete and remove this empty slot? or even better, remove while not having do deal with it at all?

3

3 Answers 3

10

You could use Array#splice, which allows to delete at a given index an amount of elements.

delete deletes the element and leaves a sparse array at this index, but it does not changes the lenght of the array.

var ids = [322, 324, 435];

ids.splice(0, 1);
//         ^     index
//            ^  count of elements to delete

console.log(ids);

Sign up to request clarification or add additional context in comments.

1 Comment

just an add on, as OP seems to want to delete by id: use indexOf(key) in the splice function....
0

Use splice instead of delete, it just set undefined

var ids = [1,2,3];
console.log(ids);
ids.splice(1,1);
console.log(ids);

Comments

0

The problem with delete is that it deletes the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined or empty.

splice(start, deleteCount) removes the element from the array:

var ids = [322, 324, 435];
ids.splice(ids.indexOf(322), ids.indexOf(322) + 1);
console.log(ids);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.