0

I have 3 arrays named "localCodes", "standardCodes", and "specialCodes". I am trying to confirm if there are any distinct values that appear in all 3 arrays.

What is the most efficient way of going about this?

EDIT:

Below is the code I was playing with, I just feel like there is a simpler way here that I am not getting

Example data set:

localCodes = [1,2,3,4]
standardCodes = [10,2,11,44]
specialCodes = [99,98,89,2]

With that set I would want to return true because 2 is found in each of the 3 arrays.

var longest = localCodes
var longFlag = 'local'
if(standardCodes.length > longest.length){
    longest = standardCodes
    longFlag = 'standard'
}
if(specialCodes.length > longest.length){
    longest = specialCodes
    longFlag = 'special'
}

for(l=0; l<longest.length; l++){
    if(longFlag == 'local'){
        //code here
    }
    if(longFlag == 'standard'){
        //code here
    }
    if(longFlag == 'special'){
        //code here
    }
}
8
  • do you have an example? what have you tried? Commented Nov 13, 2024 at 18:37
  • @qqq I just edited my code into the question Commented Nov 13, 2024 at 18:42
  • do you have the values as well and wanted result? Commented Nov 13, 2024 at 18:43
  • Are you trying to check if a specific value exits in all three? Or are you trying to find where all three overlap? Commented Nov 13, 2024 at 18:44
  • @VLAZ if ANY value exists in all 3. Once I know that there is at least 1 value that is in all 3 i'd be all set Commented Nov 13, 2024 at 18:45

1 Answer 1

1

You can map all the lists to a collection of sets and then reduce them by calling intersection.

const
  localCodes    = [ 1,  2,  3,  4],
  standardCodes = [10,  2, 11, 44],
  specialCodes  = [99, 98, 89,  2];
  
const getIntersectingValues = (...arr) => [...arr
  .map(arr => new Set(arr))
  .reduce((acc, cur) => acc.intersection(cur))];
  
const sharedValues = getIntersectingValues(
  localCodes,
  standardCodes,
  specialCodes
);

console.log(sharedValues); // [2]

If you just want a boolean, you can check the resulting size of the reduced intersection:

const
  localCodes    = [ 1,  2,  3,  4],
  standardCodes = [10,  2, 11, 44],
  specialCodes  = [99, 98, 89,  2];
  
const hasIntersectingValues = (...arr) => arr
  .map(arr => new Set(arr))
  .reduce((acc, cur) => acc.intersection(cur))
  .size > 0;
  
const hasIntersection = hasIntersectingValues(
  localCodes,
  standardCodes,
  specialCodes
);

console.log(hasIntersection); // true

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.