Hi everyone, thank you very much in advance.
I am trying to compare two arrays of objects, what I want to achieve is that if the id property coincides in both objects, add a new element "selected" with the property true to my first array of objects, I already have something set up and it works more, however it does not I feel that it is the best way since when performing a console.log in the forEach iteration I see that the elements are iterated more times than they should be.
I share my code to make myself understand better:
My first array:
optionsSelect = [
{ id:14, isActive:true, name:"rfc", value:"rfc" },
{ id:15, isActive:true, name:"nombre completo", value:"full_name" },
{ id:16, isActive:true, name:"curp", value:"curp" }
];
My second array:
templateSettings = [
{ id:14, isActive:true, name:"rfc", value:"rfc"},
{ id:15, isActive:true, name:"nombre completo", value:"full_name"}
];
My solution:
optionsSelect = [
{ id:14, isActive:true, name:"rfc", value:"rfc" },
{ id:15, isActive:true, name:"nombre completo", value:"full_name" },
{ id:16, isActive:true, name:"curp", value:"curp" }
];
templateSettings = [
{ id:14, isActive:true, name:"rfc", value:"rfc"},
{ id:15, isActive:true, name:"nombre completo", value:"full_name"}
];
optionsSelect.forEach(element => {
templateSettings.forEach(item => {
//console.log("--------------")
//console.log(item)
//console.log("--------------")
if(element.id === item.id) {
element.selected = true
}
})
})
console.log('resultado optionSelect', optionsSelect)
If you uncomment the console.log, you will see what I mean, any way to optimize the code?
Once a match is found there is no need to iterate further. That is to say that the first array must be traversed once, for each element of the first array it is necessary to traverse the second array until the match (if there is one), if we used a
for
we would have to put abreak
after a match (withforEach
you cannot ), but we can also use.some
that iterates only until the match:You can use the findIndex() method instead of the loop. Returns the position of the element (zero onwards), if it exists in the array, otherwise returns
-1
.I guess it loops
findIndex()
through the array internally and the only possible optimization is that it terminates on finding a match.