我有一个具有这样响应的API
{conditions:{,…}
individuals:[{employee_id: 12300, employee_type: "Permanent", person_id: "1211211", full_name: "John Jacobs",…},…]
page_num:5
rows:10
total_count:213}
individuals
数组中的每个条目都像这样
[ { employee_id: 12300,
employee_type: 'Permanent',
person_id: '1211211',
full_name: 'John Jacobs',
email_id: 'john_jacobs@gmail.com',
person_role: [
{rg_code: "AP",
cl_code: "12",
data : "South East Asia",
loc_code : "IN"},
{rg_code: "CD",
cl_code: "15",
data : "Middle East Asia",
loc_code : "QY"},
{rg_code: "AP",
cl_code: "12",
data : "South East Asia",
loc_code : "IN"},
{rg_code: "DF",
cl_code: "34",
data : "South East Europe",
loc_code : "FR"}
],
staffings: [ {id: 1244,
ind_id: 113322,
p_id : 112,
p_name: "Bollywood"},
{id: 1245,
ind_id: 112322,
p_id : 113,
p_name: "Tollywood"},
],
first_name: 'John',
last_name: 'Jacobs',
location:
{ country: 'India',
region: 'South Asia',
code: 'SA/IN',
name: 'Bangalore' },
assistants: [ {} ],
job_title: 'SSE-2',
person_full_name: 'John Jacobs'}
]
我试图在individuals
数组中查找在loc_code
内具有相同person_role
的重复条目的所有条目-例如-在下面给出的示例条目中,有两个条目loc_code = 'IN'
。是否可以不使用for loops
而仅使用filter
和reduce
方法来解决问题?
答案 0 :(得分:0)
您可以应用过滤器,然后缩小以为该人构造一组loc_codes。如果集合的值数量与原始人数相同,则意味着它们都不同。即使遍历整个person_role数组,即使它可能在第一个副本处停止,它的性能也可以得到改善。
var filtered = individuals.filter(el => {
return el.person_role.reduce( (prev, cur) => {
return prev.add(cur.loc_code);
}, new Set() ).size !== el.person_role.length;
});
console.log(filtered);
答案 1 :(得分:0)
您可以将唯一项目的大小与总大小进行比较。我的解决方案包括使用reduce
并将其过滤功能提取到一个单独的函数中:
function hasDuplicateLoc({ person_role }) {
const uniq = person_role.reduce((all, {loc_code}) => {
if (!all.includes(loc_code)) all.push(loc_code);
return all;
}, []);
return person_role.length !== uniq.length;
}
const result = individuals.filter(hasDuplicateLoc);
console.log(result);