4

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

1

2 Answers 2

6

Use 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; }

2
  • Thanks...Btw, what's the last line for?
    – user11554942
    Commented May 31, 2019 at 2:09
  • 1
    You mean the CSS @shiro13? It just expands the console to spare you from scrolling. Commented May 31, 2019 at 2:10
3

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)