带有对象的数组:
var myArr = [ { user: 'jane', properties: ['prop1', 'prop2'] }
{ user: 'bob', properties: ['prop1', 'prop4'] }
{ user: 'dave', properties: ['prop1', 'prop2', 'prop3'] }
{ user: 'tim', properties: ['prop4', 'prop2', 'prop3'] }
];
在纯JavaScript中是否存在一种方法,或者可能使用lodash获取具有至少一个共同属性的用户?输出应指示哪个用户与哪个用户匹配,没有重复。
我已经尝试了很多方法,但不幸的是无法获得所需的输出。
答案 0 :(得分:2)
以下解决方案使用Set
来确定是否存在匹配的属性,并结合reduce()
操作以输出匹配的用户对:
const array = [{ user: 'jane', properties: ['prop1', 'prop2'] },
{ user: 'bob', properties: ['prop1', 'prop4'] },
{ user: 'dave', properties: ['prop1', 'prop2', 'prop3'] },
{ user: 'tim', properties: ['prop4', 'prop2', 'prop3'] }];
const result = array.reduce((acc, val1, i, arr) => [
...acc,
...arr.slice(i + 1).filter(val2 => {
const properties = [...val1.properties, ...val2.properties];
return new Set(properties).size < properties.length;
}).map(val2 => [val1.user, val2.user])
], []);
console.log(result);
答案 1 :(得分:0)
您可以使用Map和Object,计算每个属性的用户出现次数,如果它与数组的长度相同,则所有用户中至少存在一个属性
let matcher = (arr) => {
let mapper = {}
arr.forEach(v => {
let { user, properties } = v
properties.forEach(v => {
if (mapper[v]) {
mapper[v].set(user, (mapper[v].get(user) || 0) + 1)
} else {
mapper[v] = new Map()
mapper[v].set(user, 1)
}
})
})
return Object.entries(mapper).some(([_, v]) => {
let total = [...v].reduce((a, [_, b]) => a + b, 0)
return total === arr.length
})
}
let arr = [{user: 'jane',properties: ['prop1', 'prop2']}, {user: 'bob',properties: ['prop1', 'prop4']}, {user: 'dave',properties: ['prop1', 'prop2', 'prop3']}, {user: 'tim',properties: ['prop4', 'prop2', 'prop3']}];
console.log(matcher(arr))
let arr2 = [{user: 'jane',properties: ['prop1', 'prop2']},{user: 'bob',properties: ['prop1', 'prop4']}]
console.log(matcher(arr2))