码迷,mamicode.com
首页 > 编程语言 > 详细

js求数组的交集/并集/差集/去重

时间:2018-12-26 20:17:11      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:方法   ===   div   res   class   OLE   ons   result   color   

      1.求交集
    var arr1 = [{name:‘name1‘,id:1},{name:‘name2‘,id:2},{name:‘name3‘,id:3}]; var arr1Id = [1,2,3] var arr2 = [{name:‘name1‘,id:1},{name:‘name2‘,id:2},{name:‘name3‘,id:3},{name:‘name4‘,id:4},{name:‘name5‘,id:5}]; var result = arr2.filter(function(v){ return arr1Id.indexOf(v.id)!==-1 // 利用filter方法来遍历是否有相同的元素 }) console.log(result);

 

      2.求并集
    let arr1 = [{name:‘name1‘,id:1},{name:‘name2‘,id:2},{name:‘name3‘,id:3}]; let arr2 = [{name:‘name1‘,id:1},{name:‘name4‘,id:4},{name:‘name5‘,id:5}]; let arr3 = arr1.concat(arr2); let result = []; var obj = []; result = arr3.reduce(function(prev, cur, index, arr) { console.log(prev, cur); obj[cur.id] ? ‘‘ : obj[cur.id] = true && prev.push(cur); return prev; }, []); console.log(result);

 

    3.求差集
    let arr1 = [{name:‘name1‘,id:1},{name:‘name2‘,id:2},{name:‘name3‘,id:3}]; let arr1Id = [1,2,3]; let arr2 = [{name:‘name1‘,id:1},{name:‘name4‘,id:4},{name:‘name5‘,id:5}]; let arr2Id = [1,4,5]; let arr3 = arr1.concat(arr2); let result = arr3.filter(function(v){ return arr1Id.indexOf(v.id)===-1 || (arr2Id.indexOf(v.id)===-1) }) console.log(result);

  

      4.去重
    let arr = [{name:‘name1‘,id:1},{name:‘name2‘,id:2},{name:‘name3‘,id:3},{name:‘name1‘,id:1},{name:‘name4‘,id:4},{name:‘name5‘,id:5}]; var obj = []; let result = arr.reduce(function(prev, cur, index, arr) { console.log(prev, cur); obj[cur.id] ? ‘‘ : obj[cur.id] = true && prev.push(cur); return prev; }, []);

 

js求数组的交集/并集/差集/去重

标签:方法   ===   div   res   class   OLE   ons   result   color   

原文地址:https://www.cnblogs.com/cx709452428/p/10180807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!