0

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) 
2
  • 1
    You can use indexOf to get the index, and then use splice to remove the element at that index from the array. Commented May 1, 2017 at 1:39
  • grade.splice(grade.indexOf('B'), 1); Commented May 1, 2017 at 1:40

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

5 Comments

the second param of splice is needed? what does the 1 for?
@Alan Jenshen - You can find that in the documentation for the splice method. For example: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Yes. By default, if no second parameter is supplied to the 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'].
in what case you need to supply other value than 1 in splice method?
Only when you want to remove more than one item from the array. The 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.