V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
pyplayer
V2EX  ›  程序员

这题如何实现比较好

  •  
  •   pyplayer · 2020-05-28 19:08:02 +08:00 · 1634 次点击
    这是一个创建于 1419 天前的主题,其中的信息可能已经有所发展或是发生改变。

    把 id 一样的合并

    var array = [
      { id: 1, spec: 1 },
      { id: 5, spec: 2 },
      { id: 2, spec: 5 },
      { id: 2, spec: 10 },
      { id: 1, spec: 12 },
      { id: 3, spec: 12 },
      { id: 4, spec: 15 },
      { id: 3, spec: 16 }
    ]
    转变为
    [
      { id: 1, spec: [ 1, 12 ] },
      { id: 5, spec: [ 2 ] },
      { id: 2, spec: [ 5, 10 ] },
      { id: 3, spec: [ 12, 16 ] },
      { id: 4, spec: [ 15 ] }
    ]
    
    

    自己的思路似乎很烦 大概思路是出现过得 id 添加到了 idarray 里,然后迭代数组每一项,id 出现过就创建一个新对象,没有就选出那个对象往数组后面添加东西

    function arrayChange(array){
      let idArray = []
      let newArray = []
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (idArray.includes(element.id)) {
          let curEle = newArray.filter(item => item.id === element.id)
          curEle[0].spec.push(element.spec)
        } else {
          idArray.push(element.id)
          let obj = {}
          obj.id = element.id
          obj.spec = []
          obj.spec.push(element.spec)
          newArray.push(obj)
        }
      }
      return newArray
    
    }
    console.log(arrayChange(array))
    
    10 条回复    2020-05-28 20:05:43 +08:00
    ynohoahc
        1
    ynohoahc  
       2020-05-28 19:23:10 +08:00   ❤️ 1
    丑丑地实现一下.
    array.reduce((total, prev) => {
    let item = total.find(item => item.id === prev.id)
    if(!item) {
    let ret = {
    id: prev.id,
    spec: [prev.spec]
    }
    total.push(ret)
    } else {
    item.spec.push(prev.spec)
    }
    return total
    }, [])
    jmc891205
        2
    jmc891205  
       2020-05-28 19:29:46 +08:00 via iPhone
    额 js 没有 hashmap 一类的东西吗
    jmc891205
        3
    jmc891205  
       2020-05-28 19:30:29 +08:00 via iPhone
    @jmc891205 每次插入都要遍历那太慢了
    rabbbit
        4
    rabbbit  
       2020-05-28 19:34:40 +08:00   ❤️ 1
    function solution(arr) {
      const table =new Map();
      for (const {id, spec} of arr) {
       if (!table.has(id)) table.set(id, []);
       table.get(id).push(spec);
     }
      const result = [];
      for (const [id, spec] of table.entries()) {
       result.push({id, spec})
     }
      return result;
    }
    pyplayer
        5
    pyplayer  
    OP
       2020-05-28 19:42:10 +08:00
    @ynohoahc 我该去复习下 reduce 了。。。
    rabbbit
        6
    rabbbit  
       2020-05-28 19:46:57 +08:00
    function solution(arr) {
      const table =new Map();
      for (const {id, spec} of arr) {
       if (!table.has(id)) table.set(id, []);
       table.get(id).push(spec);
     }
      return [...table].map(([id, spec]) => ({id, spec}));
    }
    haha370104
        7
    haha370104  
       2020-05-28 19:50:54 +08:00   ❤️ 1
    Object.entries(
    array.reduce((previousValue, currentValue) => {
    previousValue[currentValue.id] = (
    previousValue[currentValue.id] || []
    ).concat(currentValue.spec)
    return previousValue
    }, {})
    ).map(([id, spec]) => ({ id, spec }))

    这应该是我能想出来最短的写法了……
    pyplayer
        8
    pyplayer  
    OP
       2020-05-28 19:53:10 +08:00
    @rabbbit 非常感谢 我去做个笔记
    linZ
        9
    linZ  
       2020-05-28 19:53:39 +08:00
    用个 Map 不好么。。。rabit 的写法就好了
    loonghk
        10
    loonghk  
       2020-05-28 20:05:43 +08:00   ❤️ 1
    // 手痒,为了回答这个,特地注册了个账号

    function arrayChange(arr){

    var res = {};

    arr.forEach(d=>{ if(!res[d.id]){ res[d.id]=[]; } res[d.id].push(d.spec) }); // res = {1:[1,12],2:[5,10],3:[12,16],4:[15],5:[2]}

    return Object.keys(res).map(k=>({'id':k,'spec':res[k]}));

    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1032 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 19:18 · PVG 03:18 · LAX 12:18 · JFK 15:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.