- 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:男},
- ]
- //函数封装
- resArr(arr1, arr2) {
- return arr1.filter((v) => arr2.every((val) => val.id!= v.id));
- },
-
- //调用
- let newArr= this.resArr(arr1,arr2)
- console.log(newArr);
- let newArr= arr1.filter((v) =>
- arr2.every((val) => val.id != v.id)
- )
- [
- {id:1,name'小明',age:18},
- {id:3,name'小红',age:16},
- {id:4,name'小紫',age:22},
- ]
方式二:删除两个数组对象中相同的对象
- let getId = arr2.map(item=>item.id)
- console.log(set)
- let newArr = arr1.filter(item=>!getId.includes(item.id))
- console.log(newArr)
- let newArr = arr1.filter((item) => !arr2.some((ele) => ele.id === item.id));
- console.log('newArr ', newArr );
数组删除其中的对象或元素,在前端是比较常见的需求。
我现在比较常用的方法如下:
模拟数据如下
- let arr = [{"id":1,"name":"小红",},
- {"id":2,"name":"小明",},
- {"id":3,"name":"小绿"}]
方式一:假设 去掉name为小明的 这条数据
- arr.splice(
- arr.indexOf(arr.find((e) => {
- return e.name=== "小明"; }
- )
- ), 1);
- 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);
- }
- arr.forEach((item, i) => {
-
- if (item.id === idNum) { //idNum为需要删除的id idNum=3
- // console.log("找到了", item, i);
- arr.splice(i, 1)
-
- }
- })
这些方法只适合删除具有唯一标识的对象