【发布时间】:2019-02-14 18:02:25
【问题描述】:
我希望能够通过选择多个值来循环遍历对象数组并返回所有重复的结果,不包括对象的第一个实例。
这是我的尝试:
const things = [ {
location: 'Lynnwood, Wa',
keyword: 'Video Production',
user: null,
profile: null,
id: '5c659a55783fad6667853dd4' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597e4783fad6667853d8b' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597cc783fad6667853d8a' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597c7783fad6667853d89' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597c2783fad6667853d88' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597c2783fad6667853d87' },
{
location: 'Lagos, La',
keyword: 'Top Home',
user: null,
profile: null,
id: '5c659288783fad6667853d86' },
{
location: 'Lagos, La',
keyword: 'Top Home',
user: null,
profile: null,
id: '5c659219783fad6667853d84' },
{
location: 'Lagos, La',
keyword: 'Top Home',
user: null,
profile: null,
id: '5c659218783fad6667853d83' },
{
location: 'Lagos, La',
keyword: 'Top Home',
user: null,
profile: null,
id: '5c659218783fad6667853d82' } ];
function getDuplicates(arry) {
var duplicates = [];
arry.forEach((item, index) => {
if(arry.indexOf(item.location) != index && arry.indexOf(item.keyword) != index) {
duplicates.push(item);
}
});
return duplicates;
}
/*
Expected Result: (Excludes first occurance of dup but returns the rest)
[
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597cc783fad6667853d8a' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597c7783fad6667853d89' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597c2783fad6667853d88' },
{
location: 'Las Vegas',
keyword: 'Cleaners',
user: null,
profile: null,
id: '5c6597c2783fad6667853d87' },
{
location: 'Lagos, La',
keyword: 'Top Home',
user: null,
profile: null,
id: '5c659219783fad6667853d84' },
{
location: 'Lagos, La',
keyword: 'Top Home',
user: null,
profile: null,
id: '5c659218783fad6667853d83' },
{
location: 'Lagos, La',
keyword: 'Top Home',
user: null,
profile: null,
id: '5c659218783fad6667853d82' }
]
*/
【问题讨论】:
标签: javascript node.js algorithm