Merge array by replacing equal results

Asked

Viewed 955 times

4

How to merge an array by replacing the equal numbers ?

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

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


How to merge an array by substituting equal numbers only in odd arrays ? (same thing from the top question but only in odd boxes)

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

array3 would be [1, 2, 3, 6];

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

array3 would be [4, 5, 3];

  • Your second question is unclear

  • The second I didn’t understand !!!?

  • I updated the answer with the solution. Separate the KEYS into odd and even.

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 the repeated indices 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 the odd keys and pairs of the 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

Source 1 | Source 2

1

Response from: 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); 

Online Example: Jsfiddle


Response from: How to merge an array by substituting equal numbers only in odd arrays ? (same thing from the top question but only in odd boxes)

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);

Online Example: Jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.