Here are two arrays of the objects I have in js:
var arr_A = [
{Name: "Smith", CheckedOut: true},
{Name: "Jane", CheckedOut: true},
]
var arr_B = [
{Name: "Smith", CheckedIn: true},
{Name: "Paul", CheckedIn: true},
{Name: "Wagen", CheckedIn: true},
]
If duplicates are found, I want to set CheckedOut: true, CheckedIn: true
.
If it’s NOT a duplicate, I want to set either CheckedOut: false, CheckedIn: true
OR CheckedOut: true, CheckedIn: false
depending on their attribute’s values.
This is the estimated result from the example:
[
{Name: "Smith", CheckedOut: true, CheckedIn: true},
{Name: "Jane", CheckedOut: true, CheckedIn: false},
{Name: "Paul", CheckedOut: false, CheckedIn: true},
{Name: "Wagen", CheckedOut: false, CheckedIn: true},
]
This is what I have done:
let result = [];
for(var i=0; i<arr_B.length; i++){
for(var j=0; j<arr_A.length; j++) {
if(arr_A[j].Name == arr_B[i].Name) {
result.push({
Name: arr_A[j].Name,
CheckedIn: true,
CheckedOut: true
})
} else {
if(arr_A[j].CheckedOut){
result.push({
Name: arr_A[j].Name,
CheckedOut: true,
CheckedIn: false
})
} else {
result.push({
Name: arr_A[j].Name,
CheckedOut: false,
CheckedIn: true
})
}
}
}
}
5
Answers
You could take an object for collecting and initialize each value with default properties.
You can use a combination of
map
,find
, and conditional statements to iterate through both arrays and update the properties accordingly.concat
method is used to combine the items that are not duplicates from arrB.Here is a code snippet you can use to achieve the result you are looking for:
First, use Set() to get an array of unique names. Then, use map to build an object for each of the names, where you extract the properties you need from each of the source arrays:
Use an object like
userName: {Name:..., CheckedIn:... CheckedOut:...}
to accumulate values:After that,
Object.values(diff)
will return the data you’re looking for.