Comparing two arrays in Javascript to find identical values

I am faced with a challenge involving three arrays. One array contains static values, another array contains dynamic values, and the third array is intended to store values that are present in both of the other arrays.

My goal is to iterate through the arrays and identify matching values. When a match is found, that value should be added to a separate array.

This is what I am aiming for:

Array1 = ["Store1", "Store2", "Store3", "Store4"];
Array2 = ["Store6", "Store1", "Store3", "Store999"];
MatchedArray = ["Store1", "Store3"]; // should contain these values

However, I am not keen on using nested for loops like this:

  for(var arr1 = 0; arr1 < Array1.length; i++){
    for(var arr2 = 0; arr2 < Array2.length; i++){
      if(Array1[arr1].toLowerCase() == Array2[arr2].toLowerCase(){
        console.log('store found');
        duplicateArray.push(Array1[i].toLowerCase());
      }
    }
  }

I would like to explore alternative methods such as using the .map or filter function to achieve this task.

Answer №1

To achieve the desired result, you can utilize a combination of Array#filter along with Array#includes :

const arr1 = [ 'Store1', 'Store2', 'Store3', 'Store4'];
let arr2 = [ 'Store6', 'Store1', 'Store3', 'Store999'];

let result = arr2.filter(item => arr1.includes(item));
console.log(result);

Answer №2

Alternatively, you can create a versatile function to find the intersection of arrays

 var findArrayIntersection = function(){
    return Array.from(arguments).reduce(function(previous, current){
    return previous.filter(function(element){
      return current.indexOf(element) > -1;
   });
  });
 };

 var result = findArrayIntersection([1,2,3],[2,3,4]);  // You can also input multiple arrays
 console.log(result);

Answer №3

Using the filter method, we can filter out items from one array and then check if the other array contains those items by utilizing Array.includes():

var Array1 = [ 'Store1', 'Store2', 'Store3', 'Store4'];
var Array2 = [ 'Store6', 'Store1', 'Store3', 'Store999'];
var MatchedArray = Array1.filter(function(s) {
  return Array2.includes(s);
});

console.log(MatchedArray);

Answer №4

const storesArray1 = [ "ShopA", "ShopB", "ShopC", "ShopD"];
const storesArray2 = [ "ShopF", "ShopA", "ShopC", "ShopG"];

const matchingStores = storesArray1.filter(function(store) {
return storesArray2.indexOf(store) != -1;
});

matchingStores
(2) ["ShopA", "ShopC"]

Answer №5

To achieve the desired outcome, one can leverage the array.filter method.

var filtered = arr1.filter(function(val) {
    return arr2.indexOf(val) >= 0
})

The purpose of this function is to filter array elements based on a specific condition. In this case, the condition revolves around verifying the presence of 'val' in 'arr2'.

Answer №6

If you're looking to find the intersection of multiple arrays, Underscore.js provides a simple solution for this task. You can check out the documentation here.

var Array1 = [ 'Store1', 'Store2', 'Store3', 'Store4'];
var Array2 = [ 'Store6', 'Store1', 'Store3', 'Store999'];
var Array3 = [ 'Store1', 'Store5', 'Store3', 'Store201'];
var common = _.intersection( Array1 ,Array2, Array3);
console.log(common);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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

Using Vue.js to conditionally render content based on changes in a variable

I am facing a challenge in rendering a new element once the boolean variable waiting changes to true. The issue arises when transitioning from one v-if statement to another, as the boolean does not update until the first statement is completed. How can I s ...

Encountering difficulties importing in Typescript and ts-node node scripts, regardless of configuration or package type

I am facing a challenge with my React Typescript project where multiple files share a similar structure but have differences at certain points. To avoid manually copying and pasting files and making changes, I decided to create a Node script that automates ...

auto-scrolling webpage as elements come into view

Here is some jQuery code I have: $(".col-md-12").hide(); $(".button-div").hide(); $(".featurette-divider").hide(); $(".footer").hide(); $(".first").fadeIn(1000); $(".second").delay(900).fadeIn(1000); $(".third").delay(1800).fadeIn(1000); $(".fourth").dela ...

Issue with Select2: When using a remote select2 control, the tab key press does not allow for the selection of the highlighted

I have set up select2 to load ajax data into select2 based on the example provided in this link Load ajax data into select2. In the example, I can type text, use arrow keys to navigate, and then hit tab to select the highlighted item. However, in my case, ...

Tired of the premium content on Medium.com. How can I conceal premium posts that are aimed at a specific class within a parent element?

I have noticed that all Premium posts contain an element with the class ="svgIcon-use" <svg class="svgIcon-use" width="15" height="15" viewBox="0 0 15 15" style=""><path d="M7.438 2.324c.034-.099.090 123 0l1.2 3.53a.29.29 0 0 0 .26.19h3.884c.11 0 ...

Unlocking the power of dynamic text using a single form

My comment reply system is experiencing an issue where the first reply works fine, but subsequent replies are unable to get the reply text value. How can I ensure that all replies work properly based on the Razor code provided below? <h4>Comments< ...

AngularJS directive not registering event after model update

Within my angularjs application, I have implemented an element directive that is equipped with an event listener. This listener is designed to respond to a broadcast event from the controller. app.directive('listItem', function(){ return { ...

Guide on transmitting information from two separate pages to a PHP script simultaneously using an AJAX request

Looking to gather user information from a form and pass it onto another page smoothly. Origin Site <form action="destination.php" method="post"> Name: <input type="text" name="name"> Email: <input type="text" name="email"> <input typ ...

Copying the position of one object to another in THREE.js does not function as expected

Recently I started experimenting with Three.js and I’m currently working on a project where I need to position a SpotLight at the same coordinates as the camera. Below is the code snippet I’m using: $(document).ready(function() { init(); }); func ...

Express.js continues to retrieve outdated query results that have already been removed from the database

I am experiencing a strange issue with my PostgreSQL and Express.js setup. Despite updating my database with new entries and deleting old ones, it seems to only display the old data that was deleted days ago. It's almost as if it's stuck in some ...

Error: The value being evaluated in document.getElementById(x).style is not an object and is not supported

Desired Outcome for my Javascript: I am working with a div that includes an "onmouseover='getPosition(x)'" attribute which can be dynamically added and removed through my javascript by clicking a specific button. The function 'getPosition() ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

Exploring Angular.js methods to capture values from check boxes and radio buttons simultaneously

Check out my demo at https://embed.plnkr.co/R4mdZr/ Just diving into the world of Angular, I'm looking to retrieve both true values from checkboxes and radio button selections. I have a condition where if the minimum value for ingredients is one, it ...

Troubleshooting a JavaScript Script Issue in a NextJs Class

I have been working on my website and decided to incorporate an FAQ page. I used a template for the FAQ section and tried to implement Javascript in my NextJs project, but unfortunately, it's not functioning as expected. var faq = document.getEle ...

Modify Bootstrap Card Styling Using JavaScript

When the clock strikes certain evening hours on my website, the Bootstrap card's default light style no longer fits the dark theme. I've attempted to switch the card to a dark style by tying in some JavaScript code, but it's not quite doing ...

Updating content on a webpage via AJAX request without altering the original source code

Within the body of our document, referred to as "form.php," we have the following components: At the head section, there is a JavaScript code block: <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").i ...

Vue Dev Tools is not updating data in Ionic Vue 3

There seems to be an issue with the updating of Reactive and Ref data in Vue Dev Tools when changes are made in an input field bound with v-model within a form. The updated data is only visible when I interact with another component and then return to the ...

What is the best way to find the index of the smallest value in an array using JavaScript?

I recently created this function that currently outputs -1. function sayHello() { let buildingLevelsArray = [11,10,10]; var smallestIndex = buildingLevelsArray.indexOf(Math.max(buildingLevelsArray)); console.log(smallestIndex); } sayHello() ...

Unable to deploy Azure App Service due to difficulties installing node modules

My Azure Node.js App Service was created using a tutorial and further customization. The app is contained within one file: var http = require("http"); //var mongoClient = require("mongodb").MongoClient; // !!!THIS LINE!!! var server = http.createServer(f ...

Upon submitting the form, the dynamic dependent drop-down list fails to offer any available options

Hey there, I've got a form with two drop-down lists: id="dd-1" & id="dd-2". The options in id="dd-2" are generated from the database based on what's selected in id="dd-1"; I'm using onChange=getChildOf(this.value) in id="dd-1" for this ...