skip to Main Content

I have two arrays that I want to combine and then eliminate both values if duplicates appear. How can I achieve this?

arr1 = [1,2,3,4,5,6,7]

arr2 = [3,5,6,7]

I want to be left with

arr3 = [1,2,4]

Thanks

3

Answers


  1. You can use the filter method to keep only those elements that are not duplicated. An element is considered a duplicate if it appears more than once in the combined array.

    const arr1 = [1, 2, 3, 4, 5, 6, 7];
    const arr2 = [3, 5, 6, 7];
    
    const combinedArray = arr1.concat(arr2);
    
    const resultArray = combinedArray.filter(item => {
        // Count the occurrence of the current item in the combined array
        const occurrence = combinedArray.filter(x => x === item).length;
    
        // Keep the item only if its occurrence is exactly 1
        return occurrence === 1;
    });
    
    console.log(resultArray); // Output: [1, 2, 4]
    
    Login or Signup to reply.
  2. You can using the filter and includes array methods.

    Here’s an example:

    const arr1 = [1, 2, 3, 4, 5, 6, 7];
    const arr2 = [3, 5, 6, 7];
    
    const arr3 = arr1.filter(item => !arr2.includes(item));
    
    console.log(arr3);
    

    Output:

    [1,2,4]
    
    Login or Signup to reply.
  3. I think you can use count sort for this method, after that you will come to know the frequency of elements occurring in the arrays (or simply merge them and see the frequency), than you can simply select the elements with frequency 1 in the count sort array or if using stack than stack.
    Now take the unique items.

    Sol 2: using Python
    Simply merge the array (or make a list) than apply the unique property in the def unique(list1):

    # insert the list to the set
    list_set = set(list1)
    # convert the set to the list
    unique_list = (list(list_set))
    for x in unique_list:
        print x,
    

    source: GFG

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search