Question:
How to merge an array replacing 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 replacing the equal numbers only in the odd places of the arrays? (same thing as the question above but only in the odd houses)
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];
Answer:
Function to reduce the same 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 and even keys 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);