Discovering the difference between a singular array and an array of arrays

x = [1, 2,3, 5]; y = [1, [2], [3, [[4]]],[5,6]]));

I am currently facing a challenge in finding the difference between these two arrays.

function findArrayDifference(arr1, arr2) {

    var tempArr = [], difference = [];

    for (var i = 0; i < arr1.length; i++) {
        tempArr[arr1[i]] = true;
    }

    for (var i = 0; i < arr2.length; i++) {
        if (tempArr[arr2[i]]) {
            delete tempArr[arr2[i]];
        } else {
            tempArr[arr2[i]] = true;
        }
    }

    for (var key in tempArr) {
        difference.push(key);
    }

    return difference;
};

The above code snippet is what I attempted at first but it did not work as expected due to the presence of arrays within arrays. Can anyone provide some guidance on how to tackle this issue?

Answer №1

If you want to easily compare arrays, consider flattening them before checking for differences.

function arrayDifference(arr1, arr2) {
  arr1 = arr1.toString().split(',');
  arr2 = arr2.toString().split(',');

  if (arr1.length < arr2.length) {var temp = arr1; arr1 = arr2; arr2 = temp};
  return arr1.filter( element => (!arr2.includes(element)) ).map(Number);
}

var firstArray = [1, 2,3, 5]; 
var secondArray = [1, [2], [3, [[4]]],[5,6]];

var result = arrayDifference(firstArray, secondArray);

console.log(result);

Answer №2

It's crucial to flatten all arrays you wish to compare by utilizing a function that can be located here. Once the arrays are flattened, you can proceed with comparing them using another function found here

let x = [1, 2,3, 5];
let y = [1, [2], [3, [[4]], [5,6] ]]

const flatten = list => list.reduce(
    (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
)

const difference = (arr1,arr2) => {
arr1 = flatten(arr1)
arr2 = flatten(arr2)

return arr1.filter(e => arr2.indexOf(e) === -1)
               .concat(arr2.filter(e => arr1.indexOf(e) === -1))
}

console.log(difference(x,y)) // [4,6]

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

Error message when using Vue Global Filter: Value undefined is not defined

Trying to format currency, I initially attempted to use a global filter in Vue: Vue.filter('formatMoney', (val) => { if (!value) return '' val = val.toString() return val.replace(/\B(?=(\d{3})+(?!\d))/g, ",") ...

Vue - Implementing plugin as a prototype functionality

For notifications in my application, I've incorporated the euvl/vue-notification library. Each time I need to notify the user, I have to include the following code: If I'm within a Vue component: this.$notify({ group: 'panel', ...

Managing empty functions as properties of an object in a React, Redux, and Typescript environment

I'm feeling a little uncertain about how to properly test my file when using an object with a function that returns void. Below are the details. type Pros={ studentid: StudentId pageId?: PageID closeForm: () => void } When it comes to creating ...

Combining multiple HTML elements onto a single page with just one function

I am trying to dynamically import specific HTML content into a new page, rather than the entire page itself. The issue I am encountering is that I have to create a document load function for each individual item I want to import. Is there a more efficient ...

Add the content of a JavaScript variable to a label without using any scripting

Is there a way to concatenate the value of a JavaScript variable with a label without utilizing jQuery? For example: Var global_message = "1234"; <label id="my-label">Test</label> I desire the concatenated value "Test1234" to be displayed o ...

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

The maxBodySize feature is ineffective in restify

I am currently running a node app on version v0.10.33 with the Restify module ^2.8.3 installed. var app = restify.createServer(); app.use(restify.queryParser()); app.use(restify.bodyParser({ maxBodySize: 1, //Issue: The limit is not being enforced at th ...

Using Heroku to deploy NodeJS applications

I am facing an issue while trying to deploy my NodeJS project on Heroku. The project is a multiplayer game where, locally, both players enter the same map successfully. However, on Heroku, I am unable to get both players on the same map. Below is a snippe ...

Getting Angular 2 and Ionic 2 to play nice together: is it worth the effort?

Recently, I attempted to create a glossary app using Ionic 2 and encountered numerous challenges when incorporating the http service. The Angular 2 tutorials had been updated, configuring the mock server proved difficult, and the Ionic 2 documentation offe ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

Alter the color of a single character using JQuery, all while keeping the HTML tags unchanged

I'm currently working on iterating through the DOM using JQuery in order to change the color of every occurrence of the letter m. Here is what I have so far: $(document).ready(function(){ var m = "<span style='color: red;'>m</span& ...

Is it possible to utilize Angular translate to support multiple languages for individual components or modules?

Utilizing ngx-translate to switch the language of my application has proven to be quite challenging. My application consists of different languages specifically for testing purposes and is divided into separate modules with lazy loading functionality. As ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Utilize Bootstrap tooltips to display live results fetched via an AJAX call

I have a bootstrap tooltip that I am trying to populate with data from an AJAX request. The text retrieved from the request should be displayed as the title property of the tooltip. Despite successfully executing the AJAX request, I am facing two issues: ...

How to Override Certificate Expiry in JavaScript

Is there a way to bypass security for an expired certificate when making an Https post request in Javascript? I have been successful in doing this with C# and Java, but unsure about how to proceed in JavaScript. function post() { var xmlhttp; xmlhtt ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

What is the best way to access the CSS font-size property using JavaScript?

I've attempted to adjust the font size using this code: document.getElementById("foo").style.fontSize Unfortunately, this code does not return any results. The CSS styles are all defined within the same document and are not in an external stylesheet ...

Javascript problem: Trouble with event.clientX position

I found a great resource on learning javascript at this website, I'm having trouble understanding the code snippets in function XY(e, v), specifically these two lines: event.clientX + document.documentElement.scrollLeft and event.clientY + document ...

Remove child elements in Jquery that do not match the specific numbers saved in the array

I've got this array: var numbersArray = [1, 2, 4, 5] and also an unordered list in HTML <ul> <li> item 1 </li> <li> item 2 </li> <li> item 3 </li> <li> item 4 </li> <li> item 5 ...

I'm having trouble getting the aggregation of a child collection to work properly in MongoDB when attempting to apply the $count

Could someone help me troubleshoot my aggregate query? I'm trying to sum the count values for each beacon, but it keeps returning 0. Please let me know if you spot any mistakes in the query. Sample Data [ { ...