es6方法过滤掉两个数组中对象id值相等的项
let arr1=[{id:1,name:'张三'},{id:2,name:'李四'}]
let arr2=[{id:1,name:'张三'},{id:3,name:'王五'},{id:44,name:'王柳'},{id:45,name:'王琦'},]
let add=arr2.filter(item=>!arr1.some(ele=>ele.id===item.id))
console.log(add)
const arr1 = [{ id: 1, name: '网' }, { id: 2, name: '二位' }];
const arr2 = [{ id: 1, name: '老二' }, { id: 3, name: '老三' }];
// 获取到arr1的所有id集合
let arr1Ids = arr1.map(item => item.id);
// 过滤arr2中不包含arr1相同的id数组。
const result = arr2.filter(item => !arr1Ids.includes(item.id));
console.log(result); // [{id: 3, name: "老三"}];
es6取两个数组的相同项
let arr = [{ id: 1, name: 'zs' }, { id: 2, name: 'ls' }, { id: 3, name: 'ww' }, { id: 4, name: 'xm' }, { id: 5, name: 'xh' },]
let sum = [3, 4, 5]
let date = arr.filter(item => sum.indexOf(item.id) > -1)
console.log('date', date)
// 0: {id: 3, name: "ww"}
// 1: {id: 4, name: "xm"}
// 2: {id: 5, name: "xh"}
arr.forEach(item => sum.forEach(node=>{
if(item.name== node.name){
item.checked = true
item.is_required == node.is_required
item.id = node.id
}
}))
filter 过滤两个数组中相同的项
// 过滤普通元素
var a=[1,2,3,4,5]
var b=[2,3,7,8,9]
a.filter(item=>b.indexOf(item)==-1)
//过滤对象
let arr1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }];
let arr2 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 6 }, { id: 7 }];
const all = [...arr1, ...arr2].reduce((all, n) => {
n = JSON.stringify(n);
all.set(n, (all.get(n) || 0) + 1);
return all;
}, new Map());
// 找交集
for(const dataset of all){
const [key,num] = dataset;
if(num > 1){
const {id} = JSON.parse(key) ?? 0;
arr1.splice(arr1.findIndex(item => item.id === id), 1)
arr2.splice(arr2.findIndex(item => item.id === id), 1)
}
}
console.log('arr1' + JSON.stringify(arr1));
console.log('arr2' + JSON.stringify(arr2));
JS字符串和数组之间的转换
1、字符串转换为数组
var string = '123,456,789';
var stringResult = string.split(',');
console.log(stringResult) //输出["123", "456", "789"]
var string2 = 'abcdef'
var string2Result = string2.split('')
console.log(string2Result) //输出['a','b','c','d','e','f']
string2.split(",").map(Number);//输出[123,456,789]
JSON.parse("[" + string + "]"); //输出[123,456,789]
2、数组转换为字符串
var array = ['abc', 'def', 'hig']
var arrayResult = array.join(',')
console.log(arrayResult) // 输出"abc,def,hig"
array.toString()//输出"abc,def,hig"
网友评论