如何对数组中所有匹配的对象进行分组,匹配将在多个键上进行

How to grouped all matched object from Array, matching will be on multiple keys

var arrayData=[
    {
         amount:10,gameId:7 ,consoleId:3 id: 1
    },
    {
         amount:5, gameId:18 ,consoleId:3 id: 2
    },
    {
         amount:5, gameId:18 ,consoleId:3 id: 3
    },
    {
        amount:10, gameId:7 ,consoleId:3 id: 4
    },
    {
        amount:10, gameId:7 ,consoleId:4 id: 5
    },
    {
        amount:15, gameId:7 ,consoleId:3 id: 6
    }
]

匹配将在 amount、gameId、consoleId 上进行,return 它们的 Id 通过对相同的记录进行分组。 像这样输出

[[2,3],[1,4]]

lodash 或不使用 lodash

使用amount和gameId和consoleId为key,然后一起key分组

喜欢:

const key = `${item.amount}-${item.gameId}-${item.consoleId}`;

完整答案:

var getIdGroup = (arr) => {
  const mp = new Map();
  arr.forEach(item => {
    const key = `${item.amount}-${item.gameId}-${item.consoleId}`;
    const value = mp.get(key);

    if (value) {
      mp.set(key, value.concat(item.id));
    } else {
      mp.set(key, [item.id]);
    }
  });

  // only filter length >= 2
  return [...mp.values()].filter(item => item.length>=2);
}

var arrayData = [{
    amount: 10,
    gameId: 7,
    consoleId: 3,
    id: 1,
  },
  {
    amount: 5,
    gameId: 18,
    consoleId: 3,
    id: 2,
  },
  {
    amount: 5,
    gameId: 18,
    consoleId: 3,
    id: 3,
  },
  {
    amount: 10,
    gameId: 7,
    consoleId: 3,
    id: 4,
  },
  {
    amount: 10,
    gameId: 7,
    consoleId: 4,
    id: 5,
  },
  {
    amount: 15,
    gameId: 7,
    consoleId: 3,
    id: 6,
  },
];
var getIdGroup = (arr) => {
  const mp = new Map();
  arr.forEach((item) => {
    const key = `${item.amount}-${item.gameId}-${item.consoleId}`;
    const value = mp.get(key);

    if (value) {
      mp.set(key, value.concat(item.id));
    } else {
      mp.set(key, [item.id]);
    }
  });

  // only filter length >= 2
  return [...mp.values()].filter((item) => item.length >= 2);
};
console.log(getIdGroup(arrayData));