2011-11-18 16 views
5

Estoy atrapado en esto. Tengo 2 matrices, no sé la longitud de cada una, pueden ser del mismo largo o no, no sé, pero necesito crear una nueva matriz con los números no comunes en solo a (2, 10).cómo comparar dos matrices de diferente longitud si no conoce la longitud de cada una en javascript?

Para este caso:

var a = [2,4,10]; 
    var b = [1,4]; 

    var newArray = []; 

    if(a.length >= b.length){ 
     for(var i =0; i < a.length; i++){ 
      for(var j =0; j < b.length; j++){ 
       if(a[i] !=b [j]){ 
        newArray.push(b);   
       }   
      } 
     } 
    }else{} 

no sé por qué mi código nunca llegan a la primera condición y no sé qué hacer cuando b tiene mayor longitud que una.

+0

¿Quieres un comportamiento diferente cuando a es menor que b ? ¿O es esto un intento de hacerlo funcionar? – BudgieInWA

+0

Es un intento de hacerlo funcionar – bentham

+0

Además, ¿se consideran iguales los dos números que son iguales pero que no están en la misma posición? – BudgieInWA

Respuesta

7

Parece que tiene un error de lógica en su código, si entiendo sus requisitos correctamente.

Este código pondrá todos los elementos que están en a que no están en b, en newArray.

var a = [2, 4, 10]; 
var b = [1, 4]; 

var newArray = []; 

for (var i = 0; i < a.length; i++) { 
    // we want to know if a[i] is found in b 
    var match = false; // we haven't found it yet 
    for (var j = 0; j < b.length; j++) { 
     if (a[i] == b[j]) { 
      // we have found a[i] in b, so we can stop searching 
      match = true; 
      break; 
     } 
     // if we never find a[i] in b, the for loop will simply end, 
     // and match will remain false 
    } 
    // add a[i] to newArray only if we didn't find a match. 
    if (!match) { 
     newArray.push(a[i]); 
    } 
} 

Para aclarar, si

a = [2, 4, 10]; 
b = [4, 3, 11, 12]; 

continuación newArray habrá [2,10]

+0

no devuelve 2 y 10 gracias Vuelve 1,4,1,4 – bentham

+0

Aviso a newArray y obtengo 1,4,1,4 Todavía intento gracias por responder No sé por qué tu código no funciona, tienes que revisó su código? – bentham

+0

@Qeorge, he encontrado el error. Cambie la tercera línea por 'newArray.push (a [i]);' como tengo en mi edición. – BudgieInWA

2

Prueba este

var a = [2,4,10]; 
var b = [1,4]; 
var nonCommonArray = []; 
for(var i=0;i<a.length;i++){ 
    if(!eleContainsInArray(b,a[i])){ 
     nonCommonArray.push(a[i]); 
    } 
} 

function eleContainsInArray(arr,element){ 
    if(arr != null && arr.length >0){ 
     for(var i=0;i<arr.length;i++){ 
      if(arr[i] == element) 
       return true; 
     } 
    } 
    return false; 
} 
+0

gracias por responder. Acepto la respuesta anterior, pero déjame ver – bentham

+0

@bentham ¿cómo encontraste esto? – Magpie

Cuestiones relacionadas