Combining two sorted arrays in javascript while eliminating duplicate elements

Hello everyone! I am new to this and would really appreciate some assistance. I am struggling with merging two arrays and removing duplicates. I know I might be over-complicating things, but I just can't figure it out.

// Merging two sorted arrays
// [1,3,5] + [3,4] ==> [1,3,4,5]
// [1, 2, 3, 5, 6, 7] + [3, 4] ==> [1, 2, 3, 4, 5, 6, 7]

function mergeArrays (array1, array2) {
    var newArray = [];
    var pointer1 = 0;
    var pointer2 = 0;
    
    // Both pointers are still within valid indexes
    while (pointer1 < array1.length && pointer2 < array2.length) {
        if (array1[pointer1] == array2[pointer2]) {
            newArray.push(array1[pointer1]);
            pointer1++;
            pointer2++;  
        } else if (array1[pointer1] < array2[pointer2]) {
            newArray.push(array1[pointer1]);
            pointer1++;
        } else if (array1[pointer1] > array2[pointer2]) {
            newArray.push(array2[pointer2]);
            pointer2++;
        }
    }
    
    // Only one of the pointers is within a valid index
    while (pointer1 < array1.length || pointer2 < array2.length) {
        if (pointer1 >= array1.length && pointer2 < array2.length) {
            newArray.push(array2[pointer2]);
            pointer2++;
        } else if (pointer2 >= array2.length && pointer1 < array1.length) {
            newArray.push(array1[pointer1]);
            pointer1++;
        }
        
        // Both pointers have reached the ends of the arrays
        while (pointer1 == array1.length && pointer2 == array2.length) {
            return newArray;
        }
    }
}

Answer №1

To eliminate duplicates from the arrays, merge them using a Set, then convert back to an array, and finally sort the combined elements:

const mergeAndSort = (...arrs) => [...new Set(arrs.flat())].sort((a, b) => a - b)

console.log(mergeAndSort([1,3,5], [3,4]))
console.log(mergeAndSort([1, 2, 3, 5, 6, 7], [3, 4]))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to prematurely exit an outer function when there are multiple inner non-blocking function calls?

For the purpose of learning, I am working on creating a basic version of async.parallel. The description from the documentation is as follows: parallel(tasks, [callback]) Run the tasks array of functions in parallel, without waiting until the previou ...

Issue with Mongoose: Create operations are not functioning properly right after performing Delete operations

I need to refresh my collection by deleting all existing documents and then repopulating them with new data from an API call. But when I try running the delete operations first, no new documents are created. Below is a simplified version of my controller ...

the reason for the blurring of shadows in Three.js

Typically, the shadow appears as shown below: https://i.sstatic.net/5L9N2.png However, upon adjusting the parameters of directionalLight.shadow.camera directionalLight.shadow.camera.left = -50 directionalLight.shadow.camera.right = 50 directionalLight.s ...

Passing the value of an Angular component to a different component

I have a menu in my application that uses IDs to route content, and I also have a detailed view where the content should be displayed based on those same IDs. Currently, I am trying to display objects by their ID when a button is clicked. However, I' ...

Access external variables in next.js outside of its environment configuration

Currently, I am developing my application using next js as the framework. While my environment variables work smoothly within the context of next js, I am facing a challenge when it comes to utilizing them outside of this scope. An option is to use dotenv ...

What is the best way to eliminate the # symbol from a URL within a Vue.js application when utilizing a CDN

When constructing a vue.js application using CLI and vue-router, you can include mode: 'history' in the router to remove the hash from the URL. However, is there a way to eliminate the # from the URL when using Vue through a CDN? For instance, in ...

What is the best way to load a database URL asynchronously and establish a database connection prior to the initialization of an Express

My express.js app is set up to run on AWS lambda, with the database URL stored and encrypted in Amazon KMS. To access the URL, decryption using the AWS KMS service is required. // imports import mongoose from 'mongoose'; import serverless from & ...

Using Angular 2 to select with default value from a separate model

Is there a way to set the default value or link to another model while utilizing NgFor on a different model? The model intended for binding is as follows: "Bookings": {"dates": [{"date":"3-10-2016","slot":"Full"}, {"date":"4-10-2016","slot":"Full"}, {"da ...

Customizing the size of the selectInput widget in R/Shiny

I'm trying to adjust the size of the selectInput() widget in shiny using selectize.js. I've attempted to tweak various attributes listed on this page (https://github.com/selectize/selectize.js/blob/master/dist/css/selectize.css) but I can't ...

Navigate between tabs with a single click

Hey there! I'm having trouble putting together a webpage that features a sidebar. I want to make it so that clicking on one of the links at the top will switch the tab and its content accordingly. However, the current code I have isn't working an ...

Adding information to Google Cloud Firestore while disconnected from the internet

I am currently facing an issue with my code. It works perfectly fine when the application is online, but fails to execute the promise resolution or rejection when offline. I have searched through the cloud firestore documentation and found examples on qu ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...

Performing unit testing on two services that reside in separate modules using the Jasmine testing framework

I have developed a service in Angular and you can view it on this PLUNKER. In the RouteService, I am injecting CommonService, $rootRouter, ModalService. Please note the following module structure : CommonService belongs to mysampleapp.core RouteS ...

When it comes to using the jQuery get method, it may not always yield the desired results. However, utilizing it within a form context,

Upon loading my website, users are directed to a file named index.jsp. My goal is to send a get request to one of my servlets when this page loads. The initial URL is: localhost:8080/Test/ The servlet should perform an action when the URL changes to: loc ...

Guide to effectively invoking JavaScript functions using jQuery

<head> <script src="jquery-latest.js" /> <script> function resetValues(){ alert('Inside the resetValues function'); //using hexadecimal routine 1 -> 3 -> 5 -> 8 -> (11 == a) document.getElementB ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...

Calculating the sum of all elements in an array

Hi, I am currently attempting to retrieve the total value from an array (such as Arr[1] + Arr[2], and so forth). Unfortunately, I am struggling to find a solution. Below is my existing function: this.hourlyTotals = function() { var custsperhour = Math ...

Retrieving a single value from a PHP array using Codeigniter

I have a file uploader that allows me to upload multiple images. However, when I try to return the uploaded data, it only shows one of the images. Here's the code snippet: Controller: function send(){ $mariupload = $this->upload_gambar($_ ...

Transform the array into a string starting from a specific index

I have a quick question. I am trying to convert a string array with a length of 5 into a single string, but specifically from a certain index (for example starting from Array_temp[2]) until the end of the array. I have tried using the code below, which c ...

Assign the value from the list to a variable in order to execute an API call

Imagine a scenario where there's a button that displays a random joke based on a specific category. The categories are fetched using an API request from https://api.chucknorris.io/jokes/categories The jokes are generated from https://api.chucknorris. ...