Проверьте, имеет ли объединенный массив элемент из двух массивов, и обновите объединенный массив JS. - PullRequest
0 голосов
/ 28 сентября 2018

У меня есть два массива.Я объединяю его и удаляю дубликаты.Объединение выполняется с учетом всех ключей массивов (все значения ключей в объекте в массиве 1 должны совпадать со значениями в массиве 2).

var result1 = [{
    name: 'Sandra',
    email: 'sandra@example.com'
  },
  {
    name: 'John',
    email: 'johnny@example.com'
  },
  {
    name: 'Peter',
    email: 'peter@example.com'
  },
  {
    name: 'Bobby',
    email: 'bobby@example.com'
  },
  {
    name: 'Arun',
    email: 'arun@gmail.com'
  },
];

var result2 = [{
    name: 'John',
    email: 'johnny@example.com'
  },
  {
    name: 'Bobby',
    email: 'bobby@example.com'
  },
  {
    name: 'Arun',
    email: 'arun@example.com'
  }
];

var result= _.uniqWith(_.concat(result1, result2), _.isEqual)

Теперь мне нужно проверить каждый элемент объединенного массивас каждым элементом array1 и array2 и обновите объединенный массив, если они присутствуют или нет.

Таким образом, мой конечный результат должен быть таким:

var result = [{
    name: 'Sandra',
    email: 'sandra@example.com',
    presentInA: true,
    presentInB: false
  },
  {
    name: 'John',
    email: 'johnny@example.com',
    presentInA: true,
    presentInB: true
  },
  {
    name: 'Peter',
    email: 'peter@example.com',
    presentInA: true,
    presentInB: false
  },
  {
    name: 'Bobby',
    email: 'bobby@example.com',
    presentInA: true,
    presentInB: true
  },
  {
    name: 'Arun',
    email: 'arun@example.com',
    presentInA: false,
    presentInB: true
  },
  {
    name: 'Arun',
    email: 'arun@gmail.com',
    presentInA: true,
    presentInB: false
  }
];

Как мне поступить такнаилучшим образом?Я думаю, что могу сделать это с помощью итераций по всем 3 массивам, но это плохой способ сделать это.

Пожалуйста, совет.

Ответы [ 3 ]

0 голосов
/ 28 сентября 2018

Вы можете сделать что-то вроде этого

result.map(
    per => ({
        name: per.name,
        email: per.email,
        presentInA: _.find(
            result1, (o) => o.nombre === per.nombre && o.email === per.email
        ) ? true : false,
        presentInB: _.find(
            result2, (o) => o.nombre === per.nombre && o.email === per.email
        ) ? true : false,
    })
)
0 голосов
/ 28 сентября 2018

Вы можете использовать хеш-таблицу для поиска и объединения дуплей:

 // Merges objects with the same name and email, sets the [arrName] property of the merged object to true
 // also takes an optional settings object for chaining
 function merge(arr, arrName, { hash = {}, result = [] } = {}) {
   for(const { name, email } of arr) {
      // Build up a hopefully unique key
     const key = name + "@" + email;
     // If its not in the hash yet, add it to the hash and the result
     if(!hash[key]) 
        result.push(hash[key] = { name, email });
     // then set the key
     hash[key][arrName] = true;
  }
  // allow chaining by exposing both hash and result
  return { hash, result, merge: (arr, arrName) => merge(arr, arrName, { hash, result }) };
 }

Это можно использовать как:

 const { result } = merge(result1, "presentInA").merge(result2, "presentInB");

То есть O (n), но предполагается, что электронные письма несодержать два @ s.

0 голосов
/ 28 сентября 2018

Вы можете повторить над result и использовать _.some, чтобы проверить, находится ли каждый объект внутри него в result1 и result2 (и установить соответствующийсвойства presentInA и presentInB).Примерно так:

_.forEach(result, (obj) => {
   let presentInA = _.some(result1, obj);
   let presentInB = _.some(result2, obj);
   obj.presentInA = presentInA;
   obj.presentInB = presentInB;
});

var result1 = [{
    name: 'Sandra',
    email: 'sandra@example.com'
  },
  {
    name: 'John',
    email: 'johnny@example.com'
  },
  {
    name: 'Peter',
    email: 'peter@example.com'
  },
  {
    name: 'Bobby',
    email: 'bobby@example.com'
  },
];

var result2 = [{
    name: 'John',
    email: 'johnny@example.com'
  },
  {
    name: 'Bobby',
    email: 'bobby@example.com'
  },
  {
    name: 'Arun',
    email: 'arun@example.com'
  }
];

var result = _.uniqWith(_.concat(result1, result2), _.isEqual);

_.forEach(result, (obj) => {
   let presentInA = _.some(result1, obj);
   let presentInB = _.some(result2, obj);
   obj.presentInA = presentInA;
   obj.presentInB = presentInB;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
...