hi..
first of all thanks to each person of this group for their help .
as per my requirement having two arrays like below:
test1 ={11,33}
test2 ={//,"",**,33,44}
here the array lengths will not be same and all special characters are allowed.
here need to inform the user if any simpler value is there. Here in this example 33 is common.
used 2 loops to find. Still searching any smart way to do
tried the below way also but its looping twice it seems:
$.isDuplicate = function (test1, tes2) {
return $.grep(test1, function (I) {
return $.inArray(I, test2) > -1;
});
};
let result = $.isDuplicate (test1, test2).length > 0;
return result;
kindly let me know ur exp on using the below one. Let me know if you have faced any issues of using the below code.
observed its working irrespective of the arrays length:
var result = test1.filter((obj) => test2.indexOf(obj) !== -1);
if (result.length > 0) {
return true;
}
Prasad RaveendranPosted Oct 19, 2023, 1:54 AM
The code you provided using
test1.filterandtest2.indexOfis a more straightforward way to find common elements between two arrays. This code will work correctly and efficiently to identify common elements, even if the arrays have different lengths.Here's a breakdown of the code:
test1.filter((obj) => test2.indexOf(obj) !== -1)filters elements fromtest1that are found intest2. It does so by iterating through each element intest1and checking if it exists intest2usingindexOf.The filter function creates a new array with all the elements from
test1that exist intest2. The result is stored in theresultarray.If
result.lengthis greater than 0, it means there are common elements between the two arrays, and it returnstrue.This code is efficient and straightforward for your purpose. It works for arrays of different lengths and with various special characters. There should not be any issues with this code as long as the input arrays are correctly defined.