zoukankan      html  css  js  c++  java
  • js合并多维数组并去重

    合并多维数组,网上有挺多例子,可惜都不是我需求的模样,于是自己花了点时间整理了一下出来

    思路比较清晰,看到多维,想到的方法便是降维,于是,利用了对象键值对的关系用来做判断

    直接上代码了:例子只考虑了两个列表都有数据的情况,其他情况就加一下简单判断就行了

    let arr1=[
        {
            name:"测试1",
            list:[
                {
                    id:"1",
                    content:{}
                },
                {
                    id:"2",
                    content:{}
                },
                {
                    id:"3",
                    content:{}
                }
            ]
        },
        {
            name:"测试2",
            list:[
                {
                    id:"4",
                    content:{}
                },
                {
                    id:"5",
                    content:{}
                }
            ]
        }
    ]
    
    let arr2=[
        {
            name:"测试1",
            list:[
                {
                    id:"1",
                    content:{}
                },
                {
                    id:"5",
                    content:{}
                }
            ]
        },
        {
            name:"测试4",
            list:[
                {
                    id:"6",
                    content:{}
                },
                {
                    id:"7",
                    content:{}
                }
            ]
        }
    ]
    
    //临时数组,用来存储合并后的内容
    let resultList = [];
    //隐藏对象,用来判断name是否存在
    let cacheObject = {};
    //合并两个数组
    let newList = arr1.concat(JSON.parse(arr2));
    newList.forEach(item => {
        //判断对象中是否存在对应建
        if (!cacheObject[item.name]) {
            //如果不存在,直接push
            cacheObject[item.name] = item.list;
            resultList.push(item);
        } else {
            //如果存在,判断list字段里面是否相同id
            let pos = Object.keys(cacheObject).findIndex(
                key => key === item.name
            );
            //与上面临时数组对象相同(后续有时间可优化为递归遍历)
            let listItems = [];
            let cacheIds = {};
            item.list
                .concat(cacheObject[item.name])
                .forEach(sitem => {
                    //判断brandId是否存在
                    if (!cacheIds[sitem.brandId]) {
                        cacheIds[sitem.brandId] = sitem;
                        listItems.push(sitem);
                    }
                });
            resultList[pos].list = listItems;
        }
    });
  • 相关阅读:
    C++笔记(2018/2/6)
    2017级面向对象程序设计寒假作业1
    谁是你的潜在朋友
    A1095 Cars on Campus (30)(30 分)
    A1083 List Grades (25)(25 分)
    A1075 PAT Judge (25)(25 分)
    A1012 The Best Rank (25)(25 分)
    1009 说反话 (20)(20 分)
    A1055 The World's Richest(25 分)
    A1025 PAT Ranking (25)(25 分)
  • 原文地址:https://www.cnblogs.com/chao202426/p/14262819.html
Copyright © 2011-2022 走看看