Как произвести сравнение и вывести результаты сравнения объектов в массиве?

Привет, подскажите плиз, изначальный массив с хешами. Очень надо найти совпадения и представить в виде массива массивов с совпадающими айдишниками.
const arr = [
{channelid: 190,  
childrenHash: [{id: 0, hash: 'sdfsdfsfsdf'}]},
{channelid: 191,  
childrenHash: [{id: 0, hash: 'ABC'}, {id: 1, hash: 'ABC'},  {id: 2, hash: 'LLL'},  {id: 3, hash: 'LLL'},  {id: 4, hash: 'SSS'}]},
]

надо привести к виду:

const res = [
{channelid: 190,  
childrenHash: null}, //нет совпадений
{channelid: 191,  
childrenHash: [[0,1], [2,3]]}, // есть совпадения 0 с 1, и 2 с 3
]

Премного благодарен всем!
  • Вопрос задан
  • 86 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
arr.map(n => {
  const ids = Object
    .values(n.childrenHash.reduce((acc, m) => ((acc[m.hash] ??= []).push(m.id), acc), {}))
    .filter(m => m.length > 1);

  return {
    ...n,
    childrenHash: ids.length ? ids : null,
  };
})
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
kellas
@kellas
веб-разработчик
const arr = [
{channelid: 190,  
childrenHash: [{id: 0, hash: 'sdfsdfsfsdf'}]},
{channelid: 191,  
childrenHash: [{id: 0, hash: 'ABC'}, {id: 1, hash: 'ABC'},  {id: 2, hash: 'LLL'},  {id: 3, hash: 'LLL'},  {id: 4, hash: 'SSS'}]},
]

const res = arr.map(item=>{
  item.childrenHash = Object.values(
    item.childrenHash.reduce((obj,h)=>{
      obj[h.hash] = obj[h.hash] || []
      obj[h.hash].push(h.id)
      return obj
    },{})
  ).filter(l=>l.length>1)

  if (!item.childrenHash.length) item.childrenHash = null

  return item
})

console.log(JSON.stringify(res, null, 2))
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы