javascript - 如何删除包含相同 `place` 的重复 `name` 名称?

标签 javascript arrays object duplicates

我找到以下answer帮助我删除包含重复项的重复对象数组。

我做了一个fork我修改的示例。

相关功能:

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":"here","name":"stuff"},
  {"place":"there","name":"morestuff"}
]

最佳答案

您可以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></code></pre>
</div>

<div id="names">
Removed duplicate names
<pre><code></code></pre>
</div>

关于javascript - 如何删除包含相同 `place` 的重复 `name` 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590897/

相关文章:

C# 通过引用使用对象的方法

java - 我应该在循环之前还是循环中创建对象 "Random r"

javascript - PHP 根据路径名读取文件内容

c - 无法理解数组的行为

JSON 对象的 JavaScript 问题

java - 如何用通用方法找出最小值?

arrays - 附加到 UserDefaults 中的数组

javascript - Object.keys 迭代数组

javascript - 在 iframe 中使用 window.open 的唯一弹出窗口

javascript - PhantomJS/CasperJS 注入(inject)带有参数的脚本