skip to Main Content

I have two arrays:

const array1 = ["A", "S", "S", "G"]; // multiple occurrences of 'S'.
const array2 = ["S", "F", "J", "A"]; // single occurrence of 'S'.

I want to match the array2 with array1 for each of the instances. So I made a function:

const matchedArray = (array1, array2) => {
    let finalArray = [];
    array1.forEach((char, idx) => array2.includes(char) ? finalArray[idx] = `✅${char}` : finalArray[idx] = char);
    return finalArray;
}

But as you can understand that .includes() matches with all the instances of that character. So a single instance of "S" on the array2 matches with the two Ss of the array1. So the function is returning:

["✅A", "✅S", "✅S", "G"]

How can I achieve the finalArray be like:

["✅A", "✅S", "S", "G"]

4

Answers


  1. What I might do is create a dictionary of counts of the values in array2.

    { "A": 1, "S": 1, "F": 1, "J": 1 }
    

    Then use a loop to process each element of array1. If the count is greater than 0, replace and decrement. Otherwise, do nothing.

    const array1 = [ "A", "S", "S", "G" ];
    const array2 = [ "S", "F", "J", "A" ];
    const counts = { };
    
    array2.forEach(
       _ => { counts[ _ ] = ( counts[ _ ] || 0 ) + 1; }
    );
    
    const finalArray = array1.map(
       ( _, i ) => counts[ _ ] && counts[ _ ]-- ? `✅$_` : _
    );
    
    console.log( finalArray );

    Very efficient, even for long lists (O(N+M)).

    Login or Signup to reply.
  2. Just count and decrement the count.

    const
        array1 = ["A", "S", "S", "G"],
        array2 = ["S", "F", "J", "A"],
        hash = array2.reduce((h, s) => {
            h[s] = (h[s] || 0) + 1;
            return h;
        }, {}),
        result = array1.map(s => hash[s] && hash[s]-- ? '✅' + s : s);
    
    console.log(result);
    Login or Signup to reply.
  3. You could check if your array already contains the resulting product, and then not add that.

    const array1 = ["A", "S", "S", "G"]; // multiple occurrences of 'S'.
    const array2 = ["S", "F", "J", "A"]; // single occurrence of 'S'.
    
    const matchedArray = (array1, array2) => {
        let finalArray = [];
        array1.forEach((char, idx) => array2.includes(char) && !finalArray.includes(`✅${char}`) ? finalArray[idx] = `✅${char}` : finalArray[idx] = char);
        return finalArray;
    }
    
    console.log(matchedArray(array1, array2));
    Login or Signup to reply.
  4. You can just use a Set to store all the char’s that have already been used. And use the .has to to check, finally add the used chars using .add.

    eg.

    const array1 = ["A", "S", "S", "G"]; // multiple occurrences of 'S'.
    const array2 = ["S", "F", "J", "A"]; // single occurrence of 'S'.
    
    const matchedArray = (array1, array2) => {
      let finalArray = [];
      const used = new Set();
      array1.forEach((char, idx) => {
        array2.includes(char) && !used.has(char) ? finalArray[idx] = `✅${char}` : finalArray[idx] = char;
        used.add(char);
      });
      return finalArray;
    }
    
    console.log(matchedArray(array1,array2));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search