Suppose, i have an array
const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
If i want to remove the value 3
from anArray
but don't know the position of that value in the array, how can i remove that?
Note: I'm a beginner in JavaScript
Suppose, i have an array
const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
If i want to remove the value 3
from anArray
but don't know the position of that value in the array, how can i remove that?
Note: I'm a beginner in JavaScript
Share Improve this question edited May 31, 2019 at 6:38 Jack Bashford 44.1k11 gold badges55 silver badges82 bronze badges asked May 31, 2019 at 2:02 user11554942user11554942 1- Array.prototype.filter() – Ammar Commented May 31, 2019 at 2:08
2 Answers
Reset to default 6Use indexOf
to get the index, and splice
to delete:
const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
anArray.splice(anArray.indexOf("value 3"), 1);
console.log(anArray);
.as-console-wrapper { max-height: 100% !important; top: auto; }
You can use filter
filter will give you a new array with values except value 3
this will remove all the value 3
if you want only first value 3
to be removed you can use splice as given in other answer
const anArray = ['value 1', 'value 2', 'value 3', 'value 4', 'value 5'];
const filtered = anArray.filter(val=> val !== 'value 3')
console.log(filtered)