Merge array replacing equal results

4

How to merge an array by replacing the equal numbers?

Example: Home array1 = [1, 2, 3];
array2 = [2, 4, 5];

array3 would be [1, 2, 3, 4, 5]; instead of% with%

How to merge an array by replacing the equal numbers only in odd-numbered arrays? (same thing from the question from above but only in odd houses) Home Example 1:
array1 = [1, 2, 2, 3, 4, 5];
array2 = [1, 1, 2];

array3 would be [3, 4, 6];

Example 2:
array1 = [1, 2, 3, 6];
array2 = [4, 1, 5];

array3 would be [4, 4, 3];

    
asked by anonymous 03.09.2014 / 03:17

2 answers

5

Function to reduce equal occurrences

var unique = function(a) {
    return a.reduce(function(p, c) {
        if (p.indexOf(c) < 0) p.push(c);
        return p;
    }, []);
};


Concatenating and replacing repeated indexes of an array

// criando arrays e concatenando array1 e array2
var array1      = ["1", "2", "2", "3"];
var array2      = ["2", "3", "3", "4"];
var concatenado = unique( array1.concat( array2 ) );


separating odd and even keys from array with unique values

var par   = []; // agrupa chaves pares
var impar = []; // agrupa chaves impares

// separando as chaves impares e pares
for (var i=0;i<concatenado.length;i++){
    if ((i+2)%2==0) {
        impar.push(concatenado[i]);
    } else {
        par.push(concatenado[i]);
    }
}

alert(impar);
alert(concatenado);

jsfiddle online

Font 1 | Font 2

    
03.09.2014 / 03:44
1
How to merge an array by replacing the equal numbers?

var array1 = [2, 2, 3];
var array2 = [2, 4, 4];
var array3 = [array1[0]];

for(i = 1; i < array1.length; i++)
{
    var tem = false;
    for(j = 0; j < array3.length; j++){

        if (array1[i] === array3[j]){
            tem = true;
        }
    }
    if (!tem){
       array3.push(array1[i]); 
    }
}
for(i = 0; i < array2.length; i++)
{
    var tem = false;
    for(j = 0; j < array3.length; j++){

        if (array2[i] === array3[j]){
            tem = true;
        }
    }
    if (!tem){
       array3.push(array2[i]); 
    }
}

console.log(array3); 

Example Online: JSFiddle

Answer from: How to merge an array by replacing equal numbers only in odd-numbered arrays? (same question as above but only in odd houses)

var arrays1 = [1,1,2];
var arrays2 = [3,4,6];
var arrays3 = [];
var i = 0;
for(i = 0; i < arrays1.length; i+=2){                                
    arrays3.push(arrays1[i]);
}
i = 0;
for(i = 0; i < arrays2.length; i+=2){                
    var tem = false;
    for(j = 0; j < arrays1.length; j++){
        if (arrays2[i] === arrays1[j]){
            tem = true;                        
        }                    
    }   
    if (tem === false){
        arrays3.push(arrays2[i]);
    }
}
console.log(arrays3);

Example Online: JSFiddle

    
03.09.2014 / 03:45