Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

remove element from array without reindex

I have this code to add elements to an array and remove one element.

var test = []

test.push({
    bezeichnung: "test_1"
});
test.push({
    bezeichnung: "test_2"
});
test.push({
    bezeichnung: "test_3"
});



// Element aus Array entfernen
test.splice(1, 1);
console.log(test)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

My console log:

Array [ {…}, {…} ]

0: Object { bezeichnung: "test_1" }
1: Object { bezeichnung: "test_2" } // was removed
1: Object { bezeichnung: "test_3" }

But how can I realize, that the "key" from test 3 will not changed? It should be 2 instead 1. Is there a way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the keyword delete instead of splice

var test = []

test.push({
    bezeichnung: "test_1"
});
test.push({
    bezeichnung: "test_2"
});
test.push({
    bezeichnung: "test_3"
});



// Element aus Array entfernen
delete test[1];
console.log(test)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading