the unique variations found in the comparison of two arrays

I have been attempting to create code that calculates the symmetric difference between two or more arrays. The symmetric difference involves excluding elements that are present in both datasets. For more information, check out this link: https://en.wikipedia.org/wiki/Symmetric_difference

Here is the code I have written:

  //The unify function removes any duplicate elements from a vector
    function unify(arr){
        var result=arr.reduce(function(vector,num,index,self){
         var len=self.filter(function (val){
           return val===num;
         }).length;
        if (len>1){
          var pos=self.indexOf(num);
          self.splice(pos,1);
        }
        vector=self;
        return vector;
        },[]);
      
      return result;
    }
    
    function sym(args) {
      var arg = Array.prototype.slice.call(arguments); 
      var compact= arg.map(function(vector){
        return unify(vector);
      });
      
      //We compare the vectors and delete any repeated element before we concatenate them
      return compact.reduce(function(prev,next,index,self){
        for (var key in next) {
          var entry=next[key];
          var pos=prev.indexOf(entry);
          if (pos!==-1){
            prev.splice(pos,1);
            next.splice(key,1);
          }
            
        }
        return prev.concat(next);
      });
      
    }
    
    console.log(sym([1, 2, 3], [5, 2, 1, 4]));

I am puzzled as to why my code is not producing the expected result of [3,4,5]. It seems there may be an issue with how the arrays are being compared and combined.

Answer №1

Splicing the array changes the indexing and can cause values to be skipped.

For example, if prev = [1,2,3] and next = [5,2,1,4], after the first splice at key = 1, both arrays become prev = [1,3] and next = [5,1,4]. The next key is 2, which skips the entry 1 in next due to the shift caused by the splice.

Here are some solutions:

  1. Write a loop where you only increment the key when necessary. If there's a splice, don't increment since the next entry has been shifted to the current key.
  2. If you prefer using the for a in b-type loop, consider creating a duplicate constant reference for the next array.

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

Executing NodeJS awaits in the incorrect order - When using Express with SQLite3's db.all and db.run, one await is prioritized over the other

Need help running asynchronous functions in .exports, getting promises, and using the results in subsequent async functions. Despite using awaits, the second function seems to execute before the first one. sales.js = const sqlite3 = require('sqlite ...

Discover the ability to toggle button disablement or enablement in AngularJS without resorting to the ng-disabled and ng-click directives

I'm facing a challenge in implementing a button refresh feature (enable/disable) without relying on ng-disabled and ng-click. I have passed the following configuration to my directive for one or more buttons: buttonsConfig() { var button1 = { ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

Experimenting with the input type generated by the Form Helper tool

Before generating the form using Form Helper, is there a method to preview the type of input it will produce? I would like to confirm whether it will result in a select or multi-select element before loading the page. ...

"Seeking a method to identify a single unsorted element within an array that is otherwise sorted in the C programming language

Here are three scenario cases where the elements are mostly sorted except for one element: {-17, -5, -5, -2, 1, 17, 289, 17, 17, 395} | The out-of-place element is at index 6. {289, 17, 17, 17, 100, 250, 300, 1000, 5000} | The out-of-place element is at ...

Discovering the array in MongoDB that solely consists of the specified value

Let's imagine I have the following collection of documents: sections { "name":"A1", }, { "name":"A2", }, { "name":"A3", } And then we have a set of users: members { "id":5678. "sections":["A1","A2","A3"] } { "id":5679. "sections":["A1 ...

JavaScript: Toggle between 2 functions using a single click event listener

I am facing an issue with coding a Sidebar that features an animated Burger Menu Button named "navicon1". The Menu Button utilizes the "open" class to create a cool animation effect. Moreover, I aim to have the functions "openNav" and "closeNav" toggled wh ...

Enhance the speed of webview on Android devices

I have been working on an application that utilizes a webview to load both HTML and JavaScript files. Unfortunately, I have noticed a significant decrease in performance when displaying the content. Despite trying various solutions such as: webVi ...

Having issues with custom directives not functioning properly within AngularJS' RouteProvider

Currently, I'm in the process of learning AngularJS and specifically focusing on the route provider feature. I have successfully built a few pages that functioned well independently. Now, my aim is to implement the route provider into my project. In m ...

My AJAX function is not functioning as intended

I'm currently developing a time management system for my workplace. As I was coding, I implemented a feature that allows users to configure the database details similar to the setup process in WordPress. Once the data is saved successfully, I aim to d ...

Determining the size of an uninitialized character array

Can you help me understand why my code is giving me a result of 8 instead of the expected 0 when trying to calculate the length of an uninitialized char array? #include <stdio.h> int main() { char *string_t; int loc = sizeof(string_t)/sizeo ...

Is there a way to have the logo effect return to its original state when the user scrolls back up to the top of the page?

Are there any new suggestions for my issue? The previous solutions I received didn't quite work, but I'm grateful for the effort. I am currently working on a project where logo 1 fades out in the header as logo 2 fades in while scrolling down. H ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Seeking help on modfiying div content with AJAX - any tips for showing navigation using hash or anchor?

Looking to create a dynamic page that updates content within a div asynchronously while also providing users with direct access to specific content within the div by using anchors (e.g. www.website.co.uk/#page1). I've successfully implemented the upd ...

What could be the reason for my DataTables plugin not functioning properly?

I've been struggling to implement the DataTables plugin on my website. Despite ensuring that all necessary css and js files are correctly linked in my html code, the tables still don't display as expected. I have included both my html and relevan ...

Class is still visible after the media query preview is looked at, despite attempts

Our print preview library is set up to display the final product to users, but we don't want the images to actually be printed since we are using branded paper. To address this, I have included a print media query in the print.css file and added all ...

How can a server retrieve a file uploaded using FormData and Ajax on a cross-domain upload?

my website is running on localhost:8084 and I need to upload a file to localhost:8086. Below is the JavaScript code: var xhr = new XMLHttpRequest(); xhr.open("post", "http://localshot:8086"+ "?type=ajax",true); xhr.setRequestHeader("X-Reque ...

Protractor is unable to locate the password input field on Gmail using its ID

Currently, I am in the process of configuring Protractor to test my application. However, I am encountering a roadblock as it requires authentication through Gmail and I am struggling with the login process: describe('Vivace Home page', function ...

angular ng-repeat must be adjusted with modifications in the data received from a JSON file

Dealing with a JSON object that has incorrect data, my aim is to replace the existing value with one from a lookup table. However, I am unsure of how to swap out the data with values from the lookup table. lookupTable = { "pizza": function() { conso ...

Is there a method to navigate through nested JSON accessors without prior knowledge of the nested keys? The table is encountering an error

How to Handle Nested JSON Accessors in React Table Without Knowing Keys const columns = Object.keys(data).map(key=>{ return { Header: key, accessor: key } }); <ReactTable ...