Determine if multiple strings contain each other with JavaScript

I have a scenario where I am dealing with three strings that contain comma-separated numbers.

var str1 = "1,5,3";
var str2 = "2,5,1";
var str3 = "3,2,1,5"; 

My objective is to find the common elements between all three strings. The expected output should be:

var result = 1,5;

If I only have two strings, I already have a logic in place which splits the string and checks for common elements:

var array = str2.split(',');
for(var item in array) {
var contains = (str1.indexOf(array[item]) > -1);
if(contains == 1) {
    var result = array[item] + ',';
    getele2 += result;
    geteleresult = getele2.replace(/\,$/, '');
  }
}
alert(geteleresult);

However, when dealing with multiple strings, I am unsure of how to apply similar logic for sorting. If you have any ideas or suggestions, please feel free to provide them. Thank you!

Answer №1

Here is a solution using this custom function and logic:

function findCommonNumbers() {
    var nums = {};
    var numArgs = arguments.length;
    for (var i = 0; i < numArgs; i++) {
        var currentArg = arguments[i];
        var foundValues = {};

        var argSplit = currentArg.split(",");
        for (var j = 0; j < argSplit.length; j++) {
            var value = argSplit[j];
            if (!(value in foundValues)) {
                foundValues[value] = 1;
                if (!(value in nums)) {
                    nums[value] = 0;
                }
                nums[value]++;
            }
        }
    }

    var result = [];
    for (var key in nums) {
        if (nums[key] === numArgs) {
            result.push(key);
        }
    }
    return result;
}

DEMO: http://jsfiddle.net/AbCdEf/2/

This function allows you to input multiple string variables containing comma-separated numbers, and it will output the common numbers among them.

Answer №2

Consider this straightforward method:

function findCommonStrings() {
    var argumentsArray = [].slice.call(arguments),
        commonStrings = [], index;

    for (index = 1; index < argumentsArray.length; index++) {
        commonStrings = argumentsArray[index].match(RegExp((commonStrings.length ? commonStrings : argumentsArray[0].split(',')).join('|'), 'g'));
    }

    return commonStrings;
}

http://jsfiddle.net/kUqJb/

This approach is simple and can handle any number of input strings. For example:

var result = findCommonStrings(string1, string2, string3, string4);

Answer №3

One way to find common elements in multiple arrays is by using the indexOf() method.

var array1 = "1,5,3".split(',');
var array2 = "2,5,1".split(',');
var array3 = "3,2,1,5".split(',');
var output = [];

for(var i=0; i<array1.length; i++) {
    if(array2.indexOf(array1[i]) >= 0 && array3.indexOf(array1[i]) >= 0) {
        output.push(array1[i]);
    }
}

alert(output);

You can try running this code on JS Fiddle.

Answer №4

To arrange the values in a specific order, you can store them in an array and use the .sort() method.

var str1 = "10,50,30";
var str2 = "20,50,10";
var str3 = "30,20,10,50";
var getElements = "";
var resultArray = new Array();
var inputArray = str2.split(',');
for(var element in inputArray) {
    var found = (str1.indexOf(inputArray[element]) > -1);
    if(found == 1){
        var value = inputArray[element];
        resultArray.push(value);
    }
}
alert(resultArray.sort());

Check out the demonstration on JSFiddle: Demo

You can view the code here: http://jsfiddle.net/jvaibhav/BsFPW/

Answer №5

To make it simpler, consider storing the strings in an array at the beginning. The code below is a solution that can handle checking more than three strings without requiring any modifications.

str[0] = "4,6,2";
str[1] = "5,3,9";
str[2] = "7,8,5,1";

var matches = '';
for(var i=0;i<str.length-1;i++) {
    if(i==0)
        var str1 = str[i].split(',');
    else
        var str1 = matches.split(',');
    var str2 = str[i+1].split();
    var newMatches = '';
    for(var item in str2) {
        var contains = (str1.indexOf(array[item]) > -1);
        if(contains == 1) {
            var result = array[item]+',';
            newMatches += result;
        }
    }
    matches = newMatches.replace(/\,$/, '');
}

return matches;

Answer №6

Recursively calling a function is possible-

Once you identify the elements common in the first two strings,

You can then compare these commons to the following string, and continue this process,

Depending on how many arguments are passed to the function.

This scenario illustrates that it will yield two '5's if all strings contain two comma separated instances of '5'. (It is important to note that they do not have to be numbers; strings work equally well.)

function inCommon(s1, s2){
    var L1= s1.length, L2= s2.length, rx, 
    A1,  next, next1, next2, least, common= [];
    A1= (L1<= L2)? s1.split(','):s2.split(',');

    for(var i= 0, L= A1.length; i<L; i++){
        next= A1[i];
        rx= RegExp('(^|,)'+next+'(,|$)', 'g');
        next1= (s1.match(rx) || []).length;
        next2= (s2.match(rx) || []).length;
        least= Math.min(next1, next2);
        while(least--) common.push(next);
    }
    if(arguments.length>2 && common.length){
        var a= common.slice.call(arguments, 2);
        a.unshift(common.join(','));
        return inCommon.apply(window, a);
    }
    return common;
}
var str1= "1,5,3";
var str2= "2,5,1";
var str3= "3,2,1,5";

inCommon(str1, str2, str3)

/*  returned value: (Array)
1,5
*/

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

Preserving the active tab in JQuery while dynamically regenerating tabs due to database updates

I have one default static tab and two dynamic tabs that are generated based on database records. Whenever there is a change in the database, I use the $('.dynamic').remove(); JQuery remove method to refresh the elements dynamically. The dynamic ...

Creating environment-agnostic builds with the Vue webpack template

When building my Vue projects using a build server, I rely on the npm run build command provided by the Vue 2 template. This template allows me to access environment-specific data configured in files within the config directory, such as prod.env.js. The ac ...

The Flask server push appears to be functioning correctly, yet the EventSource.onmessage event is not triggering as expected

My implementation includes a route /stream that is designed to push the string 'test' every second. Upon accessing this URL (localhost:12346/stream) on Chrome, I observed that it opens a blank page and adds "test" to the page every second. This ...

Upon exiting the page, save the initial array in storage. However, the back button will load the last committed array

Currently, I have a feature on my website where users can filter articles based on their category. When the user selects the "ideas" filter, it creates a new array called "ideasFiltered" and stores it in the "filteredArticles" state. This works perfectly w ...

Enhancing JavaScript Variables Through Dynamic Ajax/PHP Interaction

I've been encountering some difficulties when trying to refresh my game. Initially, I attempted echoing the entire script each time... but that method was not aesthetically pleasing. Currently, I am experimenting with updating the variables through an ...

Tips for dividing the rows within an array using the match() function?

Within my matrix are arrays of rows. let matrix=[['hello'],['world']]; I am looking to duplicate each row within the matrix. matrix=matrix.map(x=>String(x).repeat(2)).map(x=>x.match(new RegExp??)) The desired outcome should be [ ...

Strip away all HTML attributes within a string

I am in the process of developing an internal tool that allows a designer to input exported svg code into a text area and have the html code displayed in a syntax highlighter () When they paste their code like this <svg xmlns="http://www.w3.org/20 ...

Submit form information and navigate to a different webpage without using AJAX

I need help with creating a form that redirects to another page without sending AJAX data for the current page in the action attribute. Is this possible, or is it related to PHP? const formElem = document.getElementById('form'); formE ...

The Node.js server is failing to retrieve information from the AngularJS application

Having trouble reading data sent from an AngularJS client to the server via $http.post. Can't seem to figure out where I've made a mistake. var data = $.param({ id:$scope.user_id, }); alert(JSON.stringify(data)); $http.post('/getd ...

Exploring the application of Redux in various contexts

Apologies for the vague question, but I'm a bit confused. I've recently started learning redux and now I need to integrate it into a fully-functioning project: https://github.com/CodeNinja1395/Test-task-for-inCode. There is a branch for the redux ...

Issues with Javascript code syntax

I have encountered an issue while creating a new literal control from code behind. I am able to add standard HTML into it successfully, however, when I try to insert <%= SomeDiv.ClientID %> into the literal control, it simply prints exactly what is i ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

Empower the user with the ability to interact through touch on dynamically

I am trying to make a div touchable and draggable. I have dynamically created 1 to 10 divs within another div. Currently, these divs can only be dragged using the mouse or cursor. However, I want to enable dragging through touch as well. Can anyone provi ...

Tips for implementing validation in a multi-step form as outlined in w3schools tutorial

I came across a multistep form creation tutorial on w3schools. However, the tutorial only covers generic validation (checking if a field is empty), which is not sufficient for my needs. How can I implement HTML validation (e.g., min, max, length) for text ...

Join the nested Observables array

I have an array that holds objects, each containing two properties where one is an observable value. let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}] My goal is to subscribe to the observables ...

Tips for incorporating "are you sure you want to delete" into Reactjs

I am currently working with Reactjs and Nextjs. I have a list of blogs and the functionality to delete any blog. However, I would like to display a confirmation message before deleting each item that says "Are you sure you want to delete this item?" How ...

Locate an item and add it to my online cart for purchase

Seeking assistance with my journey in learning javascript and cypress. I am having trouble locating an item on a page and adding it to the shopping cart. After using .find, I am not receiving any response. There are no errors in cypress, but the item is n ...

Retrieving a specific value from a data object using Javascript

Having a data object, I am looking to extract a specific value from it. When attempting to output the data: console.log(data); I receive an object resembling the one shown in the image below : https://i.sstatic.net/OPhgH.png The issue lies in my at ...

Ajax returns with a successful response, yet the specified action is never executed

Currently assisting with a plugin build on Wordpress and facing an issue with a basic ajax call. I am attempting to pass an object through the method 'grab_object_from_ajax_call,' but the method is not executing as expected. Below is the JavaScri ...

Breaking down a intricate JavaScript expression in order to reformat it into a different structure

As I explore the task of refactoring a legacy application, I find myself faced with complex JavaScript expressions stored in a database column. These expressions contain validation and conditional rendering logic that need to be translated into structured ...