Merge two arrays and removes all duplicates elements

function merge_array(array1, array2) {
    const result_array = [];
    const arr = array1.concat(array2);
    let len = arr.length;
    const assoc = {};

    while(len--) {
        const item = arr[len];

        if(!assoc[item]) 
        { 
            result_array.unshift(item);
            assoc[item] = true;
        }
    }

    return result_array;
}


const array1 = [1, 2, 3];

const array2 = [2, 30, 1];

console.log(merge_array(array1, array2));

JavaScript function that merges two arrays and removes all duplicate elements.

Test data:
var array1 = [1, 2, 3];
var array2 = [2, 30, 1];
// console.log(merge_array(array1, array2));
// Output: [3, 2, 30, 1]

Leave a comment

Your email address will not be published. Required fields are marked *