js deduplication of two array objects, delete the same object in the two arrays, delete an object in the array object

Simulate some data:

 let arr1 = [
   {id:1,name'小明',age:18},
   {id:2,name'小红',age:16},
   {id:4,name'小紫',age:22},
   {id:5,name'小绿',age:20},
 ]
 
 let arr2 =[
   {id:2,sex:女},
   {id:5,sex:男},
 ]

Method 1: Two arrays are compared by the id of arr1 and the id of arr2, and arr1 after deduplication is returned

//函数封装    
resArr(arr1, arr2) {
  return arr1.filter((v) => arr2.every((val) => val.id!= v.id));
},
 
//调用
let newArr= this.resArr(arr1,arr2)
console.log(newArr);

 Writing two

let newArr= arr1.filter((v) =>
  arr2.every((val) => val.id != v.id)
)

Printed results: console.log(newArr);

[
   {id:1,name'小明',age:18},
   {id:3,name'小红',age:16},
   {id:4,name'小紫',age:22},
 ]

Method 2: Delete the same object in two array objects

let getId = arr2.map(item=>item.id)  
console.log(set) 
let newArr = arr1.filter(item=>!getId.includes(item.id)) 
console.log(newArr)

Method 3: es6 removes objects with the same value in two arrays

let newArr = arr1.filter((item) => !arr2.some((ele) => ele.id === item.id));
console.log('newArr ', newArr );

Delete an object in the array, the specified object

Deleting objects or elements in an array is a common requirement in the front end.
The method I use more often now is as follows:

The simulated data is as follows:

let arr = [{"id":1,"name":"小红",},
		  {"id":2,"name":"小明",},
		  {"id":3,"name":"小绿"}]

Method 1: Assume that the data whose name is Xiao Ming is removed

arr.splice(
	arr.indexOf(arr.find((e) => { 
		return e.name=== "小明"; }
		)
), 1);

Method 2: Assume that the data with id 2 is removed

let index = -1;

for(let i=0;i<arr.length;i++){
	if(arr[i].id == idNum){ //idNum为要删除的id idNum=2 
		index = i;
	}
}

if(index>-1){
	arr.splice(index,1);
}

Method 3: Assume that the data with id 3 is removed

arr.forEach((item, i) => {

  if (item.id === idNum) { //idNum为需要删除的id idNum=3
    // console.log("找到了", item, i);
	arr.splice(i, 1)

  }
})

These methods are only suitable for deleting uniquely identified objects.

Guess you like

Origin blog.csdn.net/weixin_43743175/article/details/125257773