收藏
回答

请教下大神,不同长度数组合并问题?

arr1 = [
{uid:"111111",name:"test1"},
{uid:"222222",name:"test2"},
{uid:"333333",name:"test3"},
{uid:"444444",name:"test4"},
{uid:"555555",name:"test5"},
]

arr2 = [
{uid:"111111", score:100},
{uid:"222222", score:80},
{uid:"333333", score:85},
{uid:"444444", score:95},
]

想要合并成一个新的数组,uid没有分数据用0填充,如何在小程序的 js里面实现?

实现结果:

arr3 = [
{name:"test1",score:100},
{name:"test2",score:80},
{name:"test3",score:85},
{name:"test4",score:95},
{name:"test5",score:0},
]
回答关注问题邀请回答
收藏

6 个回答

  • 北望沣渭
    北望沣渭
    2021-12-01
    _arr2 = arr2.reduce((t, {uid,score}) => (t[uid] = score, t), {});
    arr3 = arr1.map(({uid,name}) => ({name,score: _arr2[uid] || 0}));
    
    console.info(arr3);
    
    2021-12-01
    有用 1
    回复 3
    • 无界
      无界
      2021-12-01
      非常感谢!解决问题了
      2021-12-01
      回复
    • 老张
      老张
      2021-12-01
      骚。不过arr1.length<arr2.length就漏了。。。
      2021-12-01
      1
      回复
    • 北望沣渭
      北望沣渭
      2021-12-02回复老张
      最终数据结构需要有name,而其仅存在于arr1,这个arr1.length < arr2.length 可以忽略了
      2021-12-02
      回复
  • 老张
    老张
    2021-12-01

    生并。

    随手写的,自己排错去。

    let obj3 = {}
    arr1.forEach(v=>obj[v.uid].name=v.name)
    arr2.forEach(v=>obj[v.uid].score=v.score)
    let arr3=[]
    for(let k in obj3) {
    arr3.push({
      uid:k,
      name:obj3[k].name,
      score:obj3[k].score
      })
    }
    
    2021-12-01
    有用 1
    回复 4
    • 无界
      无界
      2021-12-01
      😂
      2021-12-01
      回复
    • 老张
      老张
      2021-12-01回复无界
      已添加代码。
      2021-12-01
      回复
    • 无界
      无界
      2021-12-01
      obj[v.uid] 这里的obj 是不是 obj3 ?
      2021-12-01
      回复
    • 无界
      无界
      2021-12-01
      感谢感谢,虽然有点小问题,但思路是对的
      2021-12-01
      回复
  • 中式小面包
    中式小面包
    2021-12-01

    2021-12-01
    有用
    回复 1
    • 无界
      无界
      2021-12-01
      强!
      2021-12-01
      回复
  • 困难
    困难
    2021-12-01

    最暴力的,双重循环一个个找,找到的每一对构造一个临时对象,对象push进arr3里面。

    2021-12-01
    有用
    回复 1
    • 无界
      无界
      2021-12-01
      谢谢
      2021-12-01
      回复
  • W
    W
    2021-12-01

    用代码实现啊,就自己写呗😂

    2021-12-01
    有用
    回复 3
    • 无界
      无界
      2021-12-01
      就是不知如何用代码实现,需要帮助
      2021-12-01
      回复
    • W
      W
      2021-12-01回复无界
      你是新手吗?可以试试用map来帮助一下😂
      2021-12-01
      回复
    • 无界
      无界
      2021-12-01回复W
      好的,谢谢
      2021-12-01
      回复
  • 微喵网络
    微喵网络
    2021-12-01

    两次遍历

    2021-12-01
    有用
    回复 3
    • 无界
      无界
      2021-12-01
      可以写个样例不?谢谢了
      2021-12-01
      回复
    • 微喵网络
      微喵网络
      2021-12-01回复无界
      最基础的js知识,建议报个班吧
      2021-12-01
      回复
    • 无界
      无界
      2021-12-01
      感谢
      2021-12-01
      回复
登录 后发表内容