Reputation: 35
let a = [{
isMatched: false,
value: 'red'
}, {
isMatched: false,
value: 'green'
}];
let b = [{
isMatched: false,
value: 'red'
}, {
isMatched: false,
value: 'brown'
}];
let c = [{
isMatched: false,
value: 'white'
}, {
isMatched: false,
value: 'green'
}];
let d = [{
isMatched: false,
value: 'red'
}, {
isMatched: false,
value: 'orange'
}];
// expected output
let a = [{
isMatched: true,
value: 'red'
} {
isMatched: true,
value: 'green'
}];
let b = [{
isMatched: true,
value: 'red'
}, {
isMatched: false,
value: 'brown'
}];
let c = [{
isMatched: false,
value: 'white'
}, {
isMatched: true,
value: 'green'
}];
let d = [{
isMatched: true,
value: 'red'
}, {
isMatched: false,
value: 'orange'
}];
Upvotes: 1
Views: 59
Reputation: 634
You can combine all the arrays in one and then count the values that appear more than one:
let combinedArrays = a.concat(b, c, d);
countValues = {}
combinedArrays.forEach(function(v) {
if (isNaN(countValues[v.value])) {
countValues[v.value] = 1;
}else {
countValues[v.value] += 1;
}
})
You can then iterate through each of the arrays and check if countValues[value] > 1
then set isMatched
to true
Upvotes: 0
Reputation: 386604
You could take a Map
, check if the map contains a data set with value
as key and if not add the object to the map or set the stored object's isMatched
property to true
, as well as the actual object.
For preventing setting true
to much the value is changed to undefined
.
let a = [{ isMatched: false, value: 'red' }, { isMatched: false, value: 'green' }],
b = [{ isMatched: false, value: 'red' }, { isMatched: false, value: 'brown' }],
c = [{ isMatched: false, value: 'white' }, { isMatched: false, value: 'green' }],
d = [{ isMatched: false, value: 'red' }, { isMatched: false, value: 'orange' }];
[a, b, c, d].forEach((m => a => a.forEach(o => {
if (m.has(o.value)) {
o.isMatched = true;
const temp = m.get(o.value);
if (temp) {
temp.isMatched = true;
m.set(o.value, undefined);
}
} else {
m.set(o.value, o);
}
}))(new Map));
console.log(a);
console.log(b);
console.log(c);
console.log(d);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2