Eliminate items that are not shared between two arrays using JavaScript

I have written a function in Javascript to eliminate non-common elements between two arrays. However, I am facing an issue where my code decreases the frequency of some items while increasing others. Here is the code snippet:

function findCommonElements(arr1, arr2) {
  let common = [];
  arr1.forEach(item => {
    arr2.forEach(element => {
      if (item == element) {
        common.push(item);
      }
    });
  });
  return common;
}
console.log(findCommonElements([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));

The output from the code above is:

[ 1, 5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 5, 5 ]

Instead of the expected result:

[1, 1, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7]

After sorting

Can someone help me identify what is wrong with this code?

Answer №1

Your current approach is to push the item every time there is a unique index match between the two arrays. For instance, when 7 matches at index 3 in both arrays, it only gets pushed once. However, when the next match occurs with index 3 (first array) and index 7 (second array), only two instances of the value 7 are pushed because there are no other index matches besides 3-3 and 3-7.

A more efficient method would be to create a Set from each array, combine them, filter out elements not present in both sets, and then sort the resulting array:

function canFormPairs(a, b) {
  const setA = new Set(a);
  const setB = new Set(b);
  return [...a, ...b]
    .filter(item => setA.has(item) && setB.has(item))
    .sort((a, b) => a - b);
}
console.log(canFormPairs([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));

Answer №2

Give this a shot

function pairUpSocks(clean, dirty) {
  let matched = [];
  let oneSide = clean.filter(el => dirty.includes(el));
  let otherSide = dirty.filter(el => clean.includes(el));
  matched = oneSide.concat(otherSide);
  matched.sort(function(a, b) {
    return a - b;
  });
  return matched;
}
console.log(pairUpSocks([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));

Answer №3

Explaining the reason behind why the code provided by OP is producing inaccurate results.

The algorithm outlined in your explanation goes as follows:

  • Using 2 arrays, a and b.
  • Iterating through array a.
  • Iterating through array b.
  • If the element at index i in both arrays are equal (a[i] === b[i]), push the element from array a to the result array.

Issues identified:

  • The resulting array will have a total of m*n elements. For example, if 1 appears only once in both arrays, it will be included only once in the result. However, when dealing with multiple occurrences (e.g., 5, which occurs 2*3 times), the result will reflect this calculation and not just the sum of unique elements from both arrays (m+n instead).
  • Both input arrays may contain duplicates and are not necessarily in sorted order, leading to an unsorted final output.

Answer №4

After making some adjustments to the function, it is now operational:

function checkSockPairs(cleanSocks, dirtySocks) {
    let comparedSocks = [];
    let uniqueCleanSocks = [];

    cleanSocks.forEach((sock, index) => {
        cleanSocks.slice(index+1).forEach(otherSock => {
            if (sock === otherSock && !cleanSocks.slice(0, index).includes(sock)) {
               dirtySocks.push(otherSock);
            }
        });
    });

    uniqueCleanSocks = Array.from(new Set(cleanSocks));

    uniqueCleanSocks.forEach(cleanSock => {
        dirtySocks.forEach(dirtySock => {
            if (cleanSock === dirtySock) {
                if (!comparedSocks.includes(cleanSock)) {
                    comparedSocks.push(cleanSock);
                }
                comparedSocks.push(cleanSock);
            }
        });
   });
   
   return comparedSocks.sort();
}

console.log(checkSockPairs([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));

Answer №5

Check out this straightforward approach that utilizes the flatMap method.

Array.prototype.comparedPairs = function(arr2) {
  var arr1 = this;
  
  let compared = [arr1, arr2].flatMap(function(x) {
    return x.filter(a => arr1.indexOf(a) !== -1 && arr2.indexOf(a) !== -1);
  }).sort((a, b) => a - b);

  return compared;
}

var result = [1, 5, 6, 7, 5, 6, 5, 56].comparedPairs([1, 5, 6, 7, 8, 5, 6, 7, 8, 78]);
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

The Next.js Image component is not compatible with an external URL as the image source

I've been struggling to use the image component in Next.js with an external URL as the source, but I keep encountering an error. I followed the instructions in the official Next.js documentation and updated the next.config.js file, but unfortunately, ...

Is there a way to invoke a class method from the HTML that is specified within its constructor function?

class Welcome { constructor() { this.handlePress = this.handlePress.bind(this); this.htmlContent = `<a onclick="this.handlePress">Link</a>`; } handlePress(e) { console.log('planet'); } } The HTML structure appears ...

Is there a way for me to determine the proportion of my tests that are covered?

I am eager to determine the coverage of my project through my tests, and I am currently experimenting with the use of jest for this purpose. Here is the content of my jest.config.js: module.exports = { verbose: true, preset: '@vue/cli-plugin-unit ...

What could be causing my Ajax function to malfunction?

I've been attempting to incorporate a form that sends two javascript variables to a php script and displays the result in a new Div on the same page using an ajax function. Unfortunately, it's not functioning as expected. Here is the code snippe ...

<select> Choices are updated without the need for AJAX

Question I am working on a project with two dropdown select inputs. The first one is for selecting the country and the second one is for choosing a more specific location within that country. For example, if you choose "United Kingdom" as the country, you ...

The resizing issue of Textarea during transitions

Whenever I add the transition property to a textarea, it automatically affects the resizing function of the textarea. Is it possible to disable the transition only when resizing the textarea, but not for the textarea itself? <textarea name="" id="" cla ...

What is the best way to use alert/console in pagination to confirm if it is successfully transitioning to each page?

<div class="gridview-plp" v-for="product in productsList" :key="product.key" id="product" :items="productsList" :per-page="perPage" :current-page="currentPage"> <div class="plp-list-img1desc"> {{ product.key }} </div> <b-pag ...

Dividing text into two separate arrays in C++

I have a text file filled with various data. The lines follow a specific pattern: 6 spaces, then an integer, then a space, and finally a string. Additionally, the first line of the text file indicates the total number of lines in the file. My goal is to s ...

The phenomenon of componentDidMount being triggered before the DOM is fully mounted arises when utilizing createPortal in React

I have written a React code snippet that looks like this: import React from 'react'; import ReactDOM from 'react-dom'; import ComponentB from './ComponentB'; class ComponentA extends React.Component { constructor(props) ...

Enhance your FullCalendar experience with React by displaying extra information on your calendar

I am new to using React and FullCalendar, and I have a page layout similar to the image linked below. https://i.sstatic.net/MooTR.png Additionally, I have a list of events structured as shown: id: "9", eventId: "1", ...

Ways to implement a transition effect when the hover state is deactivated or no longer present

After applying a transition to the header using the hover pseudo-class, I noticed that it abruptly snaps back to its original position when the hover effect is removed. Is there a way to smoothly return the header to its original position using the same ...

Implement Acrobat JavaScript to enforce a mandatory separate field when a checkbox is selected

As a designer with limited coding skills, I have developed an acrobat form that includes several due date fields. These fields are only mandatory if a specific checkbox is selected. I am looking for the javascript code that will validate the requirement: ...

What is the process of inserting information into a MongoDB array?

Here is my code snippet for adding reviews to the reviews array within the restaurant object: async created(restaurantId, title, reviewer, rating, dateOfReview, review) { const restaurantsCollection = await restaurants(); let newReview = { ...

Steps to create a slideup effect using JavaScript

Upon clicking the answer text area for the first time, a message box will appear. Your Answer Thank you for contributing an answer to this platform! Please remember that this is a Q&A site, not a forum for discussion. Include specifics and share you ...

When handling cross-domain Jquery Ajax requests, the error function may unexpectedly return a success status

While attempting a cross domain GET request using jQuery AJAX, I am encountering a situation where the error function returns success as the status. The data I am expecting to be returned from the get service is: document.write("<div class=\"displ ...

I am experiencing issues with the ng-dropdown-multiselect library and it is not functioning

Check out this awesome library for creating dropdown menus using angularjs and twitter-bootstrap-3 at: . I am trying to implement the examples provided. In my html, I have: <div ng-dropdown-multiselect="" options="stringData" selected-model="stringMod ...

Using Vue Router to set a variable as a key for an object in JavaScript

In my current project, I am attempting to pass a variable as the parameter to vue-router in order to dynamically set it. The code snippet below demonstrates what I am trying to achieve: <router-link :to="{ name: notification.name, (notification.pa ...

Securely Upload Files with JavaScript

Are there any methods to utilize javascript or ajax for encrypting file uploads securely? If so, could you provide a sample code snippet or direct me to a functional example? ...

Using jQuery to verify the existence of a lengthy object

Is it possible to achieve this functionality using jQuery or other libraries? Dojo has this feature, but what about the others? $.ifObject(foo.bar.baz.qux[0]) if (foo && foo.bar && foo.bar.baz && foo.bar.baz.qux[0]) With an unkno ...

The function angular.element() is unable to locate the specified DOM element

My dilemma lies in the fact that I have a dynamic table of users extracted from a Firebase database: <table id="users"> <thead> ... </thead> <tbody> <tr ng-repeat="user in users"> <td da ...