How can you determine the number of elements that match in two arrays?

As a coding newbie, I'm looking to create a JavaScript function that compares two arrays and assigns a score based on the number of matching elements. However, when I attempt to run it in Chrome's console, I receive an error message stating that "compare is not defined."

let score = 0;
function compare(arr1, arr2) {
    for (let i = 0; i < arr2.length; i++) {
        for (let j = 0; j < arr1.length; j++) {
            if(arr1[j] === arr2[i]){
                score++;
            }   
        }
    }
}

Answer №1

If you want to determine the count of matched elements, you can utilize the .reduce() method:

let arr1 = [1, 2, 3, 4, 5],
    arr2 = [3, 4, 5, 6, 7],
    compare = (a1, a2) => arr1.reduce((a, c) => a + arr2.includes(c), 0);

console.log(compare(arr1, arr2));

Another approach is to use .filter() to create an array of matched elements and then get its length for the count.

let arr1 = [1, 2, 3, 4, 5],
    arr2 = [3, 4, 5, 6, 7],
    compare = (a1, a2) => arr1.filter(v => arr2.includes(v)).length;

console.log(compare(arr1, arr2));

Additional Resources:

Answer №2

Here is a solution that should meet your needs:

Your requested code update :

let numbers1 = [2, 5, 8, 10];
let numbers2 = [2, 4, 6, 8, 10];
function compare(numbers1,numbers2){
  let matches=0;
  const maxLength=numbers1.length>numbers2.length ? numbers2.length : numbers1.length;
  for(let j=0;j<maxLength;j++){
    if(numbers1[j]==numbers2[j]){
      matches++;
    }
  }
  return matches;
}
console.log(compare(numbers1,numbers2));

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

Comparison between Microsoft's AJAX Toolkit and jQuery

Ever since the early days of Atlas, our team has relied on Microsoft's AJAX Toolkit for all our web development needs. It wasn't until recently that we stumbled upon the jQuery/Prototype phenomenon and realized what we had been missing out on. Th ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

What causes the variable within the useEffect function to delay its value update?

const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={ ...

Uploading files on a web page using AJAX technology

I'm attempting to perform a file upload on an ajax response page. The main.php file contains basic ajax code as shown below: <html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if ...

Assign a function in one class to be equivalent to a function in a different class

What is causing this issue and how should it be resolved? class A { constructor() { console.log('constructin A') } public someMethod = (x: string) => { console.log(x) } } class B { private myA: A constructor ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

Is it possible to restructure the address 51.xx.xx.xx:33xxx:user:pass to display as user:[email protected] :33xxx instead?

I am facing an issue with my current code where it only returns one proxy because it keeps rewriting over the existing ones. I want to avoid creating a new file and instead update the 'proxies.txt' file with each new proxy. const fs = require("f ...

Unspecified variables in a Javascript bot

Currently, I am working on a project involving the Kik API to create a bot. The main goal is for the game to initiate when users type "!hangman". A boolean value called hangman activates this process and then becomes inactive. Players can then input "!ha ...

Information is being pulled from the parse database

I'm currently working on an app that allows users to view the groups they are a part of. Each group is saved in a Parse class called "grupper," with usernames stored under the "username" column and group names under "gruppe." After searching for a sc ...

Dealing with an empty req.body in an Express.js POST request

Having trouble solving this issue with a simple search. Can anyone provide clearer guidance? In the client-side code, I attempted to attach an object using xhr.send(obj). Currently, I'm trying to append to the formData object, but the result remains ...

I'm looking to combine multiple RSS feeds into a single feed, then transform the combined feed into JSON data using JavaScript. How can I achieve this?

I have been experimenting with merging multiple RSS feeds into one and converting it to JSON format. For combining the feeds, I utilized the following package: rss-combiner Below is the code snippet that successfully combines the RSS feeds: var RSSCombin ...

The functionality to disable the ES lint max length rule is malfunctioning

In trying to disable an eslint rule in a TypeScript file, I encountered an issue with a regular expression that exceeded 500 characters. As a result, an eslint warning was generated. To address this, I attempted to add an eslint comment before declaring th ...

Transforming arrays into nested objects using JavaScript

My array consists of objects structured like this: var exampleArray = [{ name: 'name1', subname: 'subname1', symbolname: 'symbol1' }, { name: 'name1', subname: 'subname11', symbolname: 'sy ...

Error encountered: `unexpected token within ES6 map() function`

Do you see any issues with this code snippet? render(){ return ( var users= this.state.users.map(user => <li key={user.id}>{user.name}</li> ) <ul>{users}</ul> ) } I am receiving an error mes ...

Is it possible to make the entire div clickable for WordPress posts, instead of just the title?

I am currently facing an issue where only the h1 element is linked to the post, but I want the entire post-info div to be clickable. Despite my efforts, I haven't been able to make the whole div clickable, only the h1 element remains so. Below is the ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

What is the best way to transfer form input data from a child component to the parent component in React?

Recently delving into the world of React, I decided to experiment with forms. My project idea was straightforward - create a form component with input fields that, upon clicking submit, would pass the input values to the parent component ('App') ...

"Implementing usort to efficiently sort multiple fields with a mix of boolean

Here is the main array structure: Array ( [0] => Array ( [active] => true [age] => 15 ) [1] => Array ( [active] => false [age] => 10 ) [3] => Array ( [active] => false ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Ways to exclusively allow cookies from my API server

I am running an Expressjs API server on localhost:4000, and my client on localhost:8008. Is there a way to ensure that my client only accepts cookies originating from my API server? At the moment, I am using fetch with credentials: 'include' to ...