must I check B is in which index? How can I get rid of B? says I have a function that receive a param that might be A,B,C
let grade = ['A','B','C']
delete grade['B']; // this won't work?
console.log(grade)
If you're really committed to the idea of using the delete operator on an array, you could it as so:
let grade = ['A', 'B', 'C'];
delete grade[grade.indexOf('B')];
Note, however, that this does not accomplish what it is that you likely want to do. More clearly, I assume you'd want the operation above to return ['A', 'C']. It actually does not. Rather, you get an undefined at index 1 (where the value B previously resided).
console.log(grade);
['A', undefined x 1, 'C']
The most appropriate operation to properly displace the B from the array would be to use Array#splice. For example:
let grade = ['A', 'B', 'C'];
grade.splice(grade.indexOf('B'), 1);
console.log(grade);
['A', 'C']
splice method. For example: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Array#splice method, it will use the length of the array less the value of the first parameter as its fallback value. In this case, that would be 3 - 1 => 2. Thus, grade.splice(grade.indexOf('B')) is the same as grade.splice(grade.indexOf('B'), 2), both of which would leave grade equal to ['A'].1 in splice method?Number-type value you supply as a second parameter simply specifies how many items to remove sequentially beginning with the index specified in the first parameter. Read the docs.
indexOfto get the index, and then usespliceto remove the element at that index from the array.grade.splice(grade.indexOf('B'), 1);