admin管理员组

文章数量:1317914

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?

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?

Share Improve this question edited Dec 1, 2016 at 20:21 Adam 45k17 gold badges107 silver badges145 bronze badges asked Dec 1, 2016 at 20:00 ChloeCodesChloeCodes 251 silver badge6 bronze badges 3
  • 5 Look at Array#filter – Ori Drori 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 :-) – ChloeCodes 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. – Ori Drori Commented Dec 2, 2016 at 18:53
Add a ment  | 

7 Answers 7

Reset to default 2

As you've found out, arrays can be "sparse" (not all indexes must have a value) and that's what you've acplished with delete. You deleted the data, but left the index.

To remove the index pletely, 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);

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' ]

Try it:

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

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

    } 
}

I think a more modern solution could look like this:

subjects.filter(subject => !(['Spanish', 'History'].includes(subject)))
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.

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

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/en-US/docs/Web/JavaScript/Reference/Operators/delete#Deleting_array_elements

You can use splice (see https://developer.mozilla/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/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);

本文标签: How do I remove items from a JavaScript ArrayStack Overflow