2

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?

3
  • 5
    Look at Array#filter Commented Dec 1, 2016 at 20:02
  • we didn't talk about filter in class yet so i did it the other way. but we probably will learn that and i'll extend it then :-) thanks so much for all the cool answers. that was really so much help :-) Commented Dec 2, 2016 at 18:35
  • 1
    Good luck with your studies. MDN is a very good resource about JS with detailed descriptions, and examples. Commented Dec 2, 2016 at 18:53

7 Answers 7

2

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);

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

1 Comment

thank you so much :-) that is exactly what i tried to do :-)
2

Use splice:

var subjects = ["Maths", "History", "English", "Science", "Spanish", "Physical Education", "History", "English", "Science", "Maths", "History", "English", "Spanish", "Physical Education"];
    
function remove(arr, item) {
    for(var i = arr.length; i--;) {
        if(arr[i] === item) {
            arr.splice(i, 1);
        }
    }
}
    
remove(subjects, "Spanish");
remove(subjects, "History");

document.write(subjects);

Output:

[ 'Maths',
  'English',
  'Science',
  'Physical Education',
  'English',
  'Science',
  'Maths',
  'English',
  'Physical Education' ]

Comments

1

Try it:

for (var index in subjects){
    if (subjects[index] == "Spanish"){
        subjects.splice(index,1);

    }
    if (subjects[index] == "History"){
        subjects.splice(index,1);

    } 
}

1 Comment

thank you :-) i did it similar to that in the end :-)
1

I think a more modern solution could look like this:

subjects.filter(subject => !(['Spanish', 'History'].includes(subject)))

Comments

0
var index = array.indexOf('history');
if (index > -1) {
    array.splice(index, 1);
}

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.

Comments

0

You could do it like this:

var subjects = [
  "Maths", "History", "English", "Science", "Spanish", 
  "Physical Education", "History", "English", "Science", 
  "Maths", "History", "English", "Spanish", "Physical Education"
];
var index = subjects.indexOf("Spanish");
subjects = Object.assign(subjects.slice(0, index), subjects.slice(index + 1, subjects.length -1);

Or by using ES6 filter:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

var subjects = [
  "Maths", "History", "English", "Science", "Spanish", 
  "Physical Education", "History", "English", "Science", 
  "Maths", "History", "English", "Spanish", "Physical Education"
];
subjects = subjects.filter((value)=> value!="Spanish");

3 Comments

thank you :-) that looks so much nice and shorter than what i had!! but i used the other answer because we didn't talk about filter yet and i also don't quite know what => does
They call it arrow functions what it does is returning the evaluated expression.
oh and remember mark my answer! and let mek now if you have any other question!
0

As you figured out the delete operator just deletes the item at a location in an array. This spot is still there, but what was in that space is just empty now (arrays can have empty spaces). See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Deleting_array_elements

You can use splice (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) to remove items by index position.

var subjects = [
  "Maths", "History", "English", "Science", "Spanish", 
  "Physical Education", "History", "English", "Science", 
  "Maths", "History", "English", "Spanish", "Physical Education"
];

for (var i = 0; i < subjects.length; i++) {
   if (subjects[i] === "Spanish") {
     subjects.splice(i, 1);
   }
   else if (subjects[i] === "History") {
     subjects.splice(i, 1);
   }
}

console.log(subjects);

Or you can use filter (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter):

var subjects = [
  "Maths", "History", "English", "Science", "Spanish", 
  "Physical Education", "History", "English", "Science", 
  "Maths", "History", "English", "Spanish", "Physical Education"
];

var isSubjectILike = function(subject){
    return subject !== "Spanish" && subject !== "History";
};
subjects = subjects.filter(isSubjectILike);

console.log(subjects);

1 Comment

thank you :-) i did it a bit like the first example you posted. we didn't talk about "filter" in class yet so i think the first way is what the teacher is looking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.