我有一个如下的多数组
[
{Name: "test1", Role: "Role1", Product: "Product4", Rate: 146, Rate_Override: 0},
{Name: "test2", Role: "Role1", Product: "Product1", Rate: 147, Rate_Override: 0},
{Name: "test3", Role: "Role1", Product: "Product1", Rate: 148, Rate_Override: 0},
{Name: "test4", Role: "Role2", Product: "Product1", Rate: 149, Rate_Override: 0},
{Name: "test5", Role: "Role3", Product: "Product2", Rate: 146, Rate_Override: 0},
{Name: "test6", Role: "Role1", Product: "Product1", Rate: 146, Rate_Override: 0},
]
如何获取与角色和产品匹配的重复记录数?
Role1 and Product4 is 1
Role1 and Product1 is 3
Role2 and Product1 is 1
Role3 and Product2 is 1
答案 0 :(得分:0)
请尝试
const a = [
{Name: "test1", Role: "Role1", Product: "Product4",Rate: 146,Rate_Override: 0},
{Name: "test2", Role: "Role1", Product: "Product1",Rate: 147,Rate_Override: 0},
{Name: "test3", Role: "Role1", Product: "Product1",Rate: 148,Rate_Override: 0},
{Name: "test4", Role: "Role2", Product: "Product1",Rate: 149,Rate_Override: 0},
{Name: "test5", Role: "Role3", Product: "Product2",Rate: 146,Rate_Override: 0},
{Name: "test6", Role: "Role1", Product: "Product1",Rate: 146,Rate_Override: 0}
]
const match = (role, product) => a.reduce((res, o) => res + (o.Role == role && o.Product == product), 0);
console.log(match('Role1', 'Product4')); // 1
console.log(match('Role1', 'Product1')); // 3
console.log(match('Role2', 'Product1')); // 1
console.log(match('Role3', 'Product2')); // 1
答案 1 :(得分:0)
您可以使用Map
并计算所需的组合属性。
var array = [{ Name: "test1", Role: "Role1", Product: "Product4",Rate: 146,Rate_Override: 0 }, { Name: "test2", Role: "Role1", Product: "Product1",Rate: 147,Rate_Override: 0 }, { Name: "test3", Role: "Role1", Product: "Product1",Rate: 148,Rate_Override: 0 }, { Name: "test4", Role: "Role2", Product: "Product1",Rate: 149,Rate_Override: 0 }, { Name: "test5", Role: "Role3", Product: "Product2",Rate: 146,Rate_Override: 0 }, { Name: "test6", Role: "Role1", Product: "Product1",Rate: 146,Rate_Override: 0 }],
keys = ['Role', 'Product'],
count = Array.from(
array.reduce(
(m, o) =>
(k => m.set(k, (m.get(k) || 0) + 1))
(keys.map(k => o[k]).join('|')),
new Map
),
([k, v]) => k.split('|').concat(v)
);
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }