¿Cómo obtener una diferencia simétrica entre dos arrays en JavaScript?

En Matemáticas la diferencia simétrica entre dos conjuntos A y B se representa como A Δ B = (A – B) ∪ (B – A)

  • Se define como un conjunto de todos los elementos que están presentes en el conjunto A o en el conjunto B, pero no en ambos.
  • En palabras simples, los elementos comunes se descartan de ambos conjuntos.

Ejemplo 1:

A = { 1, 2, 3, 4, 5, 6}
B = { 4, 5, 6, 7 }

A - B = { 1, 2, 3, 4, 5, 6} - { 4, 5, 6, 7 }
      = { 1, 2, 3 }
B - A = { 4, 5, 6, 7 } - { 1, 2, 3, 4, 5, 6}
      = { 7, 1, 2, 3 }
      
A Δ B = ( A - B ) ∪ ( B - A )
      = { 1, 2, 3 } ∪ { 7, 1, 2, 3 }
A Δ B = { 1, 2, 3, 7 }

Código:

Javascript

<script>
    /* Defining two arrays and a 
                resultant array*/
    const a = [1, 2, 3, 4, 5, 7, 9];
    const b = [5, 6, 7, 8, 9];
    const result = [];
  
    /* Defining the function with two 
    arguments array inputs */
    function difference(arr1, arr2) {
        var i = 0,
            j = 0;
        var flag = false;
  
        /* For array 1 */
        for (i = 0; i < arr1.length; i++) {
  
            /* Reseting the flag and the 
            other array iterator */
            j = 0;
            flag = false
            while (j != arr2.length) {
                if (arr1[i] == arr2[j]) {
                    flag = true;
                    break;
                }
                j++;
            }
  
            /* If value is not present in the 
            second array then push that value 
            to the resultant array */
            if (!flag) {
                result.push(arr1[i]);
            }
        }
        flag = false;
  
        /* For array 2 */
        for (i = 0; i < arr2.length; i++) {
  
            /* Reseting the flag and the 
            other array iterator */
            j = 0;
            flag = false
            while (j != arr1.length) {
                if (arr2[i] == arr1[j]) {
                    flag = true;
                    break;
                }
                j++;
            }
  
            /* If value is not present in the
            first array then push that value 
            to the resultant array */
            if (!flag) {
                result.push(arr2[i]);
            }
        }
        return result;
    }
    console.log(difference(a, b));
</script>

Producción:

[ 1, 2, 3, 4, 6, 8]

Publicación traducida automáticamente

Artículo escrito por jimishravat2802 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *