I am starting to learn coding with JavaScript and our teacher told us to search this site. There is no answer for my stuff so I wanted to ask. I hope that is OK, I have searched a lot of questions already but I can't find anything that is like my question.
My task is to go through my timetable and take out my two least favourite subject. This is what I have:
var subjects = [
"Maths", "History", "English", "Science", "Spanish",
"Physical Education", "History", "English", "Science",
"Maths", "History", "English", "Spanish", "Physical Education"
];
I said I wanted to take out Spanish and History and I did that:
for (var i = 0; i < 14; i++) {
if (subjects[i] == "Spanish") {
delete subjects[i];
}
if (subjects[i] == "History") {
delete subjects[i];
}
}
But this says it has "empty slots" :
Array [ "Maths", <1 empty slot>, "English", "Science", <1 empty slot>, "Physical Education", <1 empty slot>, "English", "Science", "Maths", 4 more… ]
But it should simply not be in there anymore. How can I do that?
As you've found out, arrays can be "sparse" (not all indexes must have a value) and that's what you've accomplished with delete
. You deleted the data, but left the index.
To remove the index completely, use the .splice()
method for this:
var subjects = [
"Maths", "History", "English", "Science", "Spanish",
"Physical Education", "History", "English", "Science",
"Maths", "History", "English", "Spanish", "Physical Education"
];
for (var i = 0; i < 14; i++) {
if (subjects[i] == "Spanish") {
subjects.splice(i, 1); // At the current index, remove one element
}
if (subjects[i] == "History") {
subjects.splice(i, 1); // At the current index, remove one element
}
}
console.log(subjects);