I need some advise on a better approach here. Say i've 2 arrays to compare, array1 & array2 and i need to check if values in array 1 exists in array 2, in PHP, i can use "array_diff" function which works every-time.
Be default, what i think of is to iterate through array1, and for each values of array1, compare that again array2, two iterations, this will be (n*n) time complexity, see my code below.
How do i improve this algorithm/code. My goal is to check if a value the one array in in another array. How do i improve this code so it won't take this much time of comparing two arrays.
const array1 = ["j1", "ff2", "3hj", "4sss", "5gh", "6ss", "7aqw"];
const array2 = ["klp3", "jks32", "44sss", "3hj", "5gh", "6ss", "7aqw"];
for (let index1 of array1){
for (let index2 of array2){
if (index1 === index2){
console.log("Exists.", "index 1 value: " + index1, "Index 2 value: " + index2)
}
}
}
I need to improve time taken. Another time complexity that is not Quadratic.