JavaScript - Issue with For Loop when Finding Symmetric Difference

Here is my solution to a coding challenge on FreeCodeCamp called "Symmetric Difference."

I'm puzzled as to why my code is returning 2, 3, 4, 6 instead of the expected 2, 3, 4, 6, 7.

 function sym(args) {
    args = Array.from(arguments);
    var newArr = [];

    function removeFirstIndex() {
        for (var i = 0; i <= args[1].length; i++) {
            if (args[1].indexOf(args[0][i]) === -1) {
                newArr.push(args[0][i]);
            }
            if (args[0].indexOf(args[1][i]) === -1) {
                newArr.push(args[1][i]);
            }
        }
        args = args.splice(2);
        args.unshift(newArr);
        newArr=[];
    }
    while (args.length>1){
        removeFirstIndex();
    }
    args=args.reduce(function(a,b){
        return a.concat(b);
    });
    args=args.filter(function(elem,pos,self){
        return self.indexOf(elem)===pos && elem!==undefined;
    });
    return args.sort();
}
sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]); // should return 2, 3, 4, 6, 7

Answer №1

Your inner for loop runs i to the length of one of the two arrays. However, you are using the same index to access an element in both arrays. This could lead to skipping elements or accessing values beyond the length of the shorter array if the arrays are of different lengths.

To address this issue, you should split the loop into two separate loops:

    for (var i = 0; i <= args[0].length; i++) {
        if (args[1].indexOf(args[0][i]) === -1) {
            newArr.push(args[0][i]);
        }
    }
    for (var i = 0; i <= args[1].length; i++) {
        if (args[0].indexOf(args[1][i]) === -1) {
            newArr.push(args[1][i]);
        }
    }

This adjustment will resolve the issue.

Additionally, you can enhance this solution by utilizing hashing, which can be achieved with a Set.

Solution with Sets:

Below is an ES6 code snippet that performs the operation using hashing. This approach eliminates the need for the indexOf operation (with a time complexity of O(n)), and instead utilizes Set.prototype.has (with an O(1) time complexity in most implementations):

function sym(...args) {
  return Array.from(
    args.map( a => new Set(a) )
      .reduce( (a, b) => new Set([...a, ...b].filter( x => !a.has(x) || !b.has(x) )) )
    ).sort();
}
var result = sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]); 
// should return 2, 3, 4, 6, 7

console.log(result);

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

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

A guide on trimming content with v-if in Vue.js

Recently, I attempted to trim the response value within a Vue condition. I require this functionality to apply the condition when the value is null or empty. <li v-if="item[0].otrodl4.trim() == ''" class="progress-step"> ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

Ways to sum up the values within a JSON object

Currently, I am using an AJAX call to fetch JSON data from an API. My goal now is to add up all the visits. This is what I have implemented so far. Any suggestions on how I can achieve that? $(document).ready(function() { var X = []; var Y = []; var d ...

Using SVG files as properties in React from a data.js file

I have a website where I store my content in a data.js file and pass it to my components using props. Everything is working correctly, except for my .svg files. When I try to display them, they do not appear. However, if I change the extension of the image ...

First-time binding of data in d3.js did not occur

I need help analyzing the following dataset: [{ label: "ABC", p1: "23", p2: "3" }, { label: "EF", p1: "4", p2: "10" }, { label: "GV", p1: "5", p2: "15" }, { label: "FD", p1: "9", p2: "5" }, { label: "SDF", p1: "20", p2: "10" },] My at ...

Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code: const { NETWORK } = require(`${basePath}/constants/network.js`); The content of network.js file is as follows: export ...

The proper way to send an email following an API request

I am currently developing an express API using node.js, and I want to implement a feature where an email is sent after a user creates an account. I have tried various methods, but none of them seem to be the perfect fit for my requirements. Here is some ps ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...

What is the best way to reference an Angular constant within a Gulp configuration file?

Is it possible to retrieve an Angular constant within a Gulp file? For example: angular.module('app').constant('env', { url: 'http://localhost:1337/' }); What is the method for accessing this constant inside a function ...

Executing function statement

I'm currently learning about React hooks, and I have a question regarding the behavior of two function expressions within different useEffect hooks. In one case, the function expression named timerId in the first useEffect is invoked automatically wit ...

retrieve information from a URL's OpenGraph metadata

Does anyone know of any comprehensive tutorials that demonstrate how to retrieve opengraph data from a URL using JavaScript, similar to the functionality seen on Facebook when pasting a link into a post or on Yahoo Mail when inserting a URL into an email? ...

The module 'react/lib/React' could not be located within the file 'ReactTestUtils.js'

Setting up unit-tests for a React Native project using ReactTestUtils is causing an issue with npm test. The error message I receive is: Cannot find module 'react/lib/React' from 'ReactTestUtils.js' I suspect that my dependencies are ...

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

Creating components in reactjs using the render function

Just a quick query – I've been diving into react js recently. Typically, when we create a component in React, we include the HTML template within the render function. I've noticed that most examples consist of small components with minimal HTM ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

I'm curious why I can only see the HTML code and not the three.js code as well

I attempted to run a sample three.js game today, but only the HTML code appeared. I've also installed three.js with npm and tried running it with the VSC Live Server, but it's not working. You can find the source code here. What should be my nex ...

What is the best way to access the properties of individual objects within an array of objects in a MongoDB MapReduce JavaScript query?

Need help referencing each property of an object within an array of objects using MongoDB MapReduce JavaScript query? Data example: { "_id": ObjectId("544ae3de7a6025f0470041a7"), "name": "Bundle 4", "product_groups": [ { "name": "camera g ...

Calling a JavaScript function using string parameters

Lately, I've stumbled upon an issue when attempting to execute a function with multiple arguments. <button type = "button" id = "clickmepls" onclick = killButton("clickmepls", "grave1")> Click me please </button> The definition of the fu ...

Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between d ...