Я считаю, что следующий отвечать очень помогает мне в удалении повторяющегося массива объектов, который содержит дубликаты.
Я сделал вилка примера, который я изменил.
Функция связана:
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"}
]
Извините, я забыл указать ожидаемый результат.
Проверь это
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' } ]
Вы можете использовать уменьшение массива с фильтром
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.info(result);
Вы можете 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>
Вместо этого вы можете использовать Array.reduce, где аккумулятор является «отфильтрованным» объектом, а следующий элемент помещается только в том случае, если аккумулятор не содержит желаемого элемента.
const uniqueArray = things.thing.reduce((acc, next) => { if (acc.find(i => i.place === next.place)) return acc; else return (acc.push(next), acc); }, []);