attempting to merge two arrays into a single union

I am looking for a way to create a new array that contains only unique values from both the first and second arrays, maintaining their original order.

This is my current approach:

function union(first, second) {
return first.filter(function(value) {
  return second.indexOf(value) === -1;
})

.concat(second.filter(function(value){
  return first.indexOf(value) === -1;
}))
}

The expected output should be as follows:

union([2, 1], [2, 3]);
// -> [2, 1, 3]
union(['html', 'css', 'javascript'], ['php', 'css', 'sql']);
// -> ["html", "css", "javascript", "php", "sql"]
union(
  ['a', 'link', 'to', 'the', 'past'],
  ['the', 'adventure', 'of', 'link']
)

Answer №1

Combine arrays using spread syntax and then utilize the Set method to filter out duplicates, resulting in a new array with only unique values.

function mergeArrays(arr1, arr2) {
  return [...new Set([...arr1, ...arr2])];
}
console.log(mergeArrays([2, 1], [2, 3]));
console.log(mergeArrays(['html', 'css', 'javascript'], ['php', 'css', 'sql']));
console.log(mergeArrays(
  ['a', 'link', 'to', 'the', 'past'],
  ['the', 'adventure', 'of', 'link']
));

Answer №2

Quick solution:

const arr1 = ['apple', 'banana', 'orange']
const arr2 = ['grape', 'banana', 'kiwi']
const mergedArray = [...new Set([...arr1, ...arr2])];
console.log(mergedArray);

// mergedArray = [ 'apple', 'banana', 'orange', 'grape', 'kiwi' ]

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

Embed a YouTube video within the product image gallery

Having trouble incorporating a YouTube video into my Product Image Gallery. Currently, the main product photo is a large image with thumbnails that change it. You can see an example on my website here. Whenever I attempt to add a video using the code below ...

Encountering an ExpressionChangedAfterItHasBeenCheckedError in Angular 6 when selecting an option from a dropdown menu

How can we fix the error mentioned below through code changes? Situation An input dropdown UI is safeguarded against unintentional value changes by a modal. However, triggering an event (such as click or focus) on the dropdown leads to the ExpressionChan ...

Techniques for passing an integer array to a queue interface in Java

I need assistance with creating a queue in Java that accepts an integer array as arguments: Queue<int[]> q = new LinkedList<>(); q.push(new int[]{0, 0}); Encountered error message: Error: cannot find symbol q.push(new int[]{0, 0}); ^ ...

How can you display a doughnut chart with a custom color to represent empty or no data, including doughnut rings?

I have integrated a doughnut chart from chartjs into my Vue project using vue-chartjs. Currently, the doughnut chart does not display anything when there is no data or all values are empty. Is there a way to customize the color and show the entire doughnu ...

How to implement a timeout feature in JavaScript/TypeScript for cloud functions

I'm currently facing an issue with trying to delay certain actions using Cloud Firestore. Despite my attempts, the setTimeout/setInterval functions don't seem to be working as expected in my code. export const onTimerCreate = functions.firestore ...

Is `console.log()` considered a native function in JavaScript?

Currently, I am utilizing AngularJS for my project. The project only includes the angular.min.js file without any additional references to other JavaScript files. The code snippet responsible for sending requests to the server is as shown below: var app = ...

Tidying up JQuery with automatic selection of the next div and navigation item

My primary question revolves around optimizing the code for a functionality where clicking on 5 images reveals a related div while hiding the rest. As a newcomer to jQuery, I feel that my current implementation is somewhat messy and lengthy. Seeking advice ...

Cloning jQuery with varied PHP array value

So, I have the given PHP values: PHP: <?php $names = array("Mike","Sean","Steve"); ?> <script type="text/javascript"> var name_data = <?php echo json_encode($names); ?>; </script> <div class="container"> <div cl ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

Mixing without Collections

After initially posting this question yesterday, I realized that I needed to clean up my code before proceeding. However, for my assignment, I am required to create a JavaScript quiz where the questions and answer choices are shuffled every time a user ret ...

Determining the optimal times to utilize traditional loops instead of array helpers

After writing in Javascript for some time, I've become quite comfortable with using array helpers. However, there have been moments where traditional for loops seem more practical and easier to work with compared to array helpers. Can you provide me w ...

Trigger a function in AngularJS when a div is scrolled to within a specific number of pixels from the bottom of the screen

I am experimenting with the AngularJS infinite-scroll directive. Below is the code snippet: angular.module('infiniteScroll', []) .directive('infiniteScroll', [ "$window", function ($window) { return { link:funct ...

Prepare an email message for sending

Currently, I'm working on an app using officejs. My goal is to extract content from an Excel worksheet and insert it into an Outlook email. However, I don't want the email to be automatically sent by the system. Instead, I would like the new emai ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

Code has been loaded successfully for react-loadable Chunks, however it has not been

Encountering a problem while trying to implement chunks in my React app using react-loadable Everything functions perfectly on webpack-dev-server in development mode. However, when I build the project and deploy it to the server, async components are ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

Switching over a function from jQuery to Mootools

Here is a snippet of code used to refresh a specific DIV by making a request for data. The current function works as intended, but we are looking to migrate to Mootools. JavaScript Code: <script> jQuery.noConflict(); (function(jQuery) { jQuery ...

Single-use binding format

I am a beginner with Angular and I have some doubts about the syntax used in Angular. In AngularJS, we can achieve one-time binding like this: <p>{{::myVar}}</p> In Angular, I know we can do it differently. <p [innerText]="myVar"></ ...