Как удалить повторяющееся имя `place`, которое содержит то же` name`? - PullRequest
0 голосов
/ 09 апреля 2019

Я считаю, что следующий ответ мне очень помогает в удалении дублирующегося массива объектов, который содержит дубликаты.

Я сделал вилку из примера, который я модифицировал.

Функция связана:

const uniqueArray = things.thing.filter((thing,index) => {
  return index === things.thing.findIndex(obj => {
    return JSON.stringify(obj) === JSON.stringify(thing);
  });
});

Например, у меня есть:

[
  {"place":"here","name":"stuff"},
  {"place":"there","name":"morestuff"},
  {"place":"there","name":"morestuff"},
  {"place":"herehere","name":"stuff"}
]

Будет возвращено:

[
  {"place":"here","name":"stuff"},
  {"place":"there","name":"morestuff"},
  {"place":"herehere","name":"stuff"}
]

Как удалить повторяющееся place имя, которое содержит тот же name?

Ожидаемый результат:

[
  {"place":"here","name":"stuff"},
  {"place":"there","name":"morestuff"}
]

Ответы [ 3 ]

2 голосов
/ 09 апреля 2019

Вы можете reduce по массиву объектов. Проще говоря, если объект со значением ключа, совпадающим с текущим объектом, уже существует в аккумуляторе, не добавляйте его снова.

Вот функция, которая позволяет вам указать, какую клавишу вы хотите дедуплицировать:

const arr = [
  {"place":"here","name":"stuff"},
  {"place":"there","name":"morestuff"},
  {"place":"there","name":"morestuff"},
  {"place":"herehere","name":"stuff"}
];

// Accepts an array and a key that should have the
// duplicates removed
function remove(arr, key) {

  // Iterate over the array passing in the accumulator
  // and the current element
  return arr.reduce((acc, c) => {

    // If there is an object in the accumulator with the
    // same key value as the current element simply return the
    // accumulator
    if (acc.find(obj => obj[key] === c[key])) return acc;

    // Otherwise add the current element to the accumulator
    // and return it
    return acc.concat(c);
  }, []);
}

function showJSON(arr, id) {
  const json = JSON.stringify(arr, null, 2);
  document.querySelector(`#${id} code`).textContent = json;
}

// remove duplicate places
showJSON(remove(arr, 'place'), 'places');

// remove duplicate names
showJSON(remove(arr, 'name'), 'names');
<div id="places">
Removed duplicate places
<pre><code>
Удалены повторяющиеся имена
2 голосов
/ 09 апреля 2019

Проверьте это

  const things = [
        {"place":"here","name":"stuff"},
        {"place":"there","name":"morestuff"},
        {"place":"there","name":"morestuff"},
        {"place":"herehere","name":"stuff"}
    ]

    const uniqueArray = things.reduce((accumulator, currentValue) => {
        if (accumulator.find(a => a.name === currentValue.name))
            return accumulator;
        else
            return (accumulator.push(currentValue), accumulator);
    }, []);

Вывод

    [ { place: 'here', name: 'stuff' },
      { place: 'there', name: 'morestuff' } ]
0 голосов
/ 09 апреля 2019

Вы можете использовать уменьшение массива с фильтром

let data=[
  {"place":"here","name":"stuff"},
  {"place":"there","name":"morestuff"},
  {"place":"there","name":"morestuff"},
  {"place":"herehere","name":"stuff"}
]

// Using reduce() to separate the contents we want
let result=data.reduce((acc,value)=>{
  if(acc.filter(val=>val.name==value.name).length==0) // checking the accumulator if it already containsa the value
  {
    acc.push(value); // if the array returned is of length==0 we can push in it
  }
return acc;

},[])
console.log(result);

См. Фильтр массива , Array.prototype.Reduce

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...