最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to remove a specific value from an array in JavaScript? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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; }

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)

发布评论

评论列表(0)

  1. 暂无评论