Form a union of arrays provided as arguments in a function

I am stuck trying to create a function that combines the arrays provided as parameters into one union. Unfortunately, I keep encountering an error message:

JavaScript TypeError: Cannot read property 'length' of undefined

Here is my current approach:

function uniteUnique(arr) {

  var newArr = arguments[0];

  //Iterate through arguments
  for (let i = 0; i<arr.length-1; i++){
    console.log(arguments[i]);

    //Iterate through values in the second argument
    for (let y =0; y<arguments[i+1].length; y++){

      //Iterate through values in the first argument
      for (let z=0; z<arguments[i].length; z++){
        if (arguments[i+1][y] !== arguments[i][z]){
          newArr.push(arguments[i+1][y]);
        }

      }
    }
  }
  return arr;
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

The desired output should be [1, 3, 2, 5 ,4], which represents a unique union of values from all three arrays given. However, I continue to encounter the same error.

TypeError: Cannot read property 'length' of undefined

Answer №1

If you're looking to merge three arrays into one while eliminating any duplicate elements, you can utilize the code snippet below:

const arr1 = [1, 2, 3];
const arr2 = [3, 4, 5];
const arr3 = [4, 5, 6];

const mergedArray = [...new Set([...arr1, ...arr2, ...arr3])];

console.log(mergedArray);

Answer №2

Utilizing the power of ES6 features

function mergeArrays(...arrays){
let newArray = []

//Combining arrays using spread operator
arrays.forEach(array=>{
  newArray = [...array,...newArray]
})

//Removes duplicate elements and keeps only unique ones
newArray = [...new Set(newArray)]

console.log("Unique values:" + newArray)

}

mergeArrays([1,2,3,1],[0,4,1])

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

Retrieve the identifier from the database by selecting the edit button within a jQuery DataTable

Whenever the delete button of a specific row is clicked, I need to retrieve the id of that row from the database. Once I have obtained the id, it needs to be sent to the controller to carry out the deletion of that row. I attempted to approach this issue ...

Error: Unable to establish connection with local host (::1) on port 50106

I am currently in the process of developing a Discord bot using Node.js and erela.js. However, I encountered an error when attempting to retrieve the server that handles erela: A node error occurred: connect ECONNREFUSED ::1:50106 2020-05-01T21:23:19.367 ...

What is the best way to add a style to the currently active link on a NavLink component using the mui styled() function

I have a custom NavLink component that I want to style with an ".active" class when it is active. However, I am not sure how to achieve this using the "styled()" function in MUI. Does anyone know how to accomplish this? Below is the code for my custom Nav ...

What are some techniques for obtaining the second duplicate value from a JSON Array in a React JS application by utilizing lodash?

Currently, I am tackling a project that requires me to eliminate duplicate values from a JSON array object in react JS with specific criteria. My initial attempt was to use the _.uniqBy method, but it only retained the first value from each set of duplicat ...

"Troubleshooting the slow loading of PDF files when using React's render-pdf feature

After creating a table with the ability for each row to generate and download a PDF using render-pdf npm, I encountered an issue. When the user clicks the download button, the PDF preview opens on a new page. However, there are problems with rendering as a ...

Combining Angular with MVC partial views

What I'm Looking For I require a sequence of interactive screens that progress to the next screen upon button click. Each previous screen should collapse while loading the new screen using a partial view from the MVC backend. My Current Setup Curre ...

Setting up a Babel configuration for a full-stack MERN application

After giving up on learning Rails, I shifted my focus to diving into Node using the MERN stack. Despite completing courses by Stephen Grider and Andrew Mead on Udemy, as well as all the Code School JS courses, I feel like I'm not making much progress. ...

Verify whether the user is obstructing third-party domain

I've encountered a recurring issue where many of our support calls pertain to images not loading due to users blocking Amazon S3 or a similar third-party service. I rely on third-party services for hosting images, videos, and certain JavaScript elemen ...

Extracting the Hidden Gems in a Nested Object

My goal is to extract a specific value from a two-level deep object data structure. To begin, I am storing the data in a variable within a function, like so: getTargetId() { if (this.authenticationService.isAuthenticated()) { const userInfo = ...

"Authentic JavaScript Universal Time Coordinated (UTC) Date

I've been struggling to keep my dates in UTC within my JavaScript application. Surprisingly, the Date's getTimezoneOffset() method does not return a value of 0, which I expected it to do. This seems crucial for accurately converting dates between ...

Is the Webpack vendors JS bundle in Vue CLI containing unlisted code that is not in the dependencies or package-lock.json file?

An information security auditing tool flagged an outdated library with known vulnerabilities in our webpack-bundled chunk-vendors.js file generated using Vue CLI: The library in question is YUI 2.9.0. It appears that this library is not fully included, a ...

How can Angular 2 and Firebase be used to search for an email match within all Firebase authentication accounts?

Is there a method to verify the existence of an email within Firebase auth for all registered accounts when users sign up? Can AngularFireAuth be utilized in an Angular 2 service for this purpose? My authentication system is established, but now I am work ...

Transform the jQuery UI Slider to be clickable rather than draggable

Currently using jQuery UI 1.10.3 and aiming to create a slider widget that is not draggable. The intention is for the user to click on specific values along the slider instead. I previously attempted using eventDefault in the slider's start method, b ...

Load components in NextJS lazily without utilizing `next/dynamic`

Currently, I am in the process of developing a component (Editor) that should always be lazy-loaded in React applications. However, I need it to be compatible with any React app. While I have successfully implemented lazy loading with Create React App usi ...

Use jQuery or Javascript to transform URLs within paragraphs into clickable hyperlinks

As someone who is new to javascript but familiar with jQuery, I've been attempting to utilize the following code to convert instances of www. and http in p tags into clickable links. The issue I'm facing is that while I can implement this code, ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

Nesting / Mulled / JS - Uploading Files - Form's end is unexpectedly reached

I have successfully implemented the upload file functionality in my Nest.js server application, but I am facing an issue when trying to use it with JavaScript/React. @Post('upload') @UseInterceptors(FileInterceptor('file')) upl ...

I'm looking to use gulp-inject to dynamically add the contents of a file into my index.html - how can I achieve

Here are the steps I followed: gulp.task('watch-index-html', function () { gulp.watch(files, function (file) { return gulp.src('index/index.html') .pipe(inject(gulp.src(['index/base3.html']), { ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Troubleshooting the Issue of Table Append not Functioning in Live Environment

I'm currently in the process of developing a website using Bootstrap, and I'm facing an issue where one of the tables gets cleared out and updated with new data when a button is clicked. This functionality works perfectly fine during testing on V ...