一、filter、some方法刪除兩個(gè)數(shù)組對象中id相同的對象
let arr1=[{id:1,name:"張三"},{id:2,name:"李四"}]
let arr2=[{id:1,name:"張三"},{id:3,name:"老劉"},{id:6,name:"老牛"},{id:8,name:"老萬"},]
let add=arr1.filter(item=>!arr2.some(ele=>ele.id===item.id)); //數(shù)組1新數(shù)組
let add1=arr2.filter(item=>!arr1.some(ele=>ele.id===item.id)); //數(shù)組2新數(shù)組
1. filter方法
定義和用法
- filter() 方法創(chuàng)建一個(gè)新的數(shù)組,新數(shù)組中的元素是通過檢查指定數(shù)組中符合條件的所有元素。
注意: filter() 不會(huì)對空數(shù)組進(jìn)行檢測。
注意: filter() 不會(huì)改變原始數(shù)組。
語法
array.filter(function(currentValue,index,arr), thisValue)
參數(shù)說明
2. some方法
定義和用法
-
some() 方法用于檢測數(shù)組中的元素是否滿足指定條件(函數(shù)提供)。
-
some() 方法會(huì)依次執(zhí)行數(shù)組的每個(gè)元素:
1.如果有一個(gè)元素滿足條件,則表達(dá)式返回true , 剩余的元素不會(huì)再執(zhí)行檢測。
2.如果沒有滿足條件的元素,則返回false。
注意: some() 不會(huì)對空數(shù)組進(jìn)行檢測。
注意: some() 不會(huì)改變原始數(shù)組。
語法
array.some(function(currentValue,index,arr),thisValue)
參數(shù)說明
二、刪除數(shù)組中id相同的數(shù)據(jù)
- 方法一
let arr1=[{id:1,name:"張三"},{id:3,name:"老劉"},{id:3,name:"老劉"},{id:8,name:"老萬"},]
let hash = [];
const newArr = arr1.reduce((pre, cur) => {
hash[cur.id] ? '' : (hash[cur.id] = true && pre.push(cur));
return pre;
}, []);
console.log('過濾掉重復(fù)的數(shù)據(jù)newArr===', newArr);
JavaScript中reduce()詳解及使用方法。
- 方法二:
let arr = [
{id: 1, name: 'Tom'},
{id: 2, name: 'Jerry'},
{id: 3, name: 'Mickey Mouse'}
];
function removeById(arr, id) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
arr.splice(i, 1);
break;
}
}
return arr;
}
console.log(removeById(arr, 2));
// [{id: 1, name: 'Tom'}, {id: 3, name: 'Mickey Mouse'}]
三、刪除數(shù)組中的某個(gè)指定元素
let index = this.fileList.indexOf(filename)
if (index > -1) {
this.fileList.splice(index, 1)
}
其中fileList為我的數(shù)組,我要找到fileList中為filename的元素,并把它刪除。
用indexOf()函數(shù)找到他的位置index,如果沒有找到這個(gè)元素那么index將會(huì)等于-1;
用splice()函數(shù)刪除第index位置的1個(gè)元素;
這樣就可以把filename刪除了。文章來源:http://www.zghlxwxcb.cn/news/detail-776823.html
四、刪除數(shù)組中的指定數(shù)組對象
this.fileList.forEach((value,index,array)=>{
if(value.filename == obj.filename){
array.splice(index,1)
}
})
刪除指定數(shù)組對象,是通過判斷對象某個(gè)屬性(最好是具有唯一性的屬性)是否相等,進(jìn)而將這整個(gè)數(shù)組對象刪除的。
我這里是刪除fileList中包含屬性為指定filename的數(shù)組對象。文章來源地址http://www.zghlxwxcb.cn/news/detail-776823.html
五、已知對象id,刪除數(shù)組中的對應(yīng)對象
var arr = [
{id: 1, name: 'Tom'},
{id: 2, name: 'Jerry'},
{id: 3, name: 'Mickey Mouse'}
];
function filterArr(list,id){
list = list.filter(item => item.id !== id)
return list
}
var a=filterArr(arr,2);
到了這里,關(guān)于JavaScript中刪除兩個(gè)數(shù)組對象中id相同的對象以及根據(jù)id刪除數(shù)組中對象。的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!