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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks...Btw, what's the last line for?
You mean the CSS @shiro13? It just expands the console to spare you from scrolling.
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)

Comments

Your Answer

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