Two deletion methods: 1. Use splice() function, syntax "arr.splice(arr.findIndex(item=>item.id===id), 1)"; 2. Use filter () function filtering, syntax "arr=arr.filter((num,index)=>{return index!==val})".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
The first splice(index,num);
index represents the subscript position of the array element, and num represents deletion The number of
arr.splice(arr.findIndex(item => item.id === id), 1) //item 只是参数可以写成 i 或者 v 都可以 , //后面的额id是数组的id,是不能随便写的,如果你数组里面写的是id,这里就写id,如果数组里面写的是num,那这里就写num , //=== 后面的id是你想要删除的元素的id号,同理,如果你数组里面写的是num,那这里就是num号 , //1是你要删除1个元素的意思
findIndex(); is the position where the subscript of an element is found
As shown in the figure, there are three elements in this array. Now we need to delete this id It is the element of 24, so our code should be written like this
arr.splice(arr.findIndex(item => item.id === 24), 1)
If you print it, you will find that the element with the id of 24 has been deleted!
The second arr.filter()
filter() method creates a new array. The elements in the new array are determined by checking all elements in the specified array that meet the conditions. .
Note: filter() will not detect empty arrays.
Note: filter() will not change the original array.
array.filter(function(currentValue,index,arr), thisValue)
//这样就删除啦 arr = arr.filter((num,index)=>{return index !== val})
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to delete specified elements from es6 array. For more information, please follow other related articles on the PHP Chinese website!