I have two arrays that are identical in structure.
let TaskArray=[
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3"},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3"},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3"},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3"},
{"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3"},
{"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3"},
{"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3"},
{"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3"},
{"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3"},
{"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"}
]
let TaskDetailsArray = [
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3"},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3"},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3"},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3"},
]
I need to compare the two arrays and set the flag isAssigned to true if an item from the second array is found by id in the first array, and false otherwise.
matcheArray = [
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3"},
{"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3"},
{"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3"},
{"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3"},
{"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3"},
{"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"}
]
The code below works ok, but I'm not sure whether there is a better way to accomplish it. Please suggest.
for (var i = 0; i < TaskArray.length; i ) {
for (var k = 0; k < this.TaskDetailsArray.length; k ) {
if (TaskArray[i].TaskID == this.TaskDetailsArray[k].TaskID) {
if (!this.TaskDetailsArray[k].isAssigned) {
this.TaskDetailsArray[k].isAssigned = true;
};
}
}
CodePudding user response:
const comparedArray = taskArray.map(item => {
return {
...item,
isAssigned: TaskDetailsArray.some(secondItem => secondItem.TaskId === item.TaskId );
}
})