JavaScript - analyzing multiple arrays against a single array

Can anyone help me determine whether 'buns' or 'duns' has the most elements in common with 'me'? I need a method to accomplish this task.

var buns = ['bap', 'bun', 'bop'];
var duns = ['dap', 'dun', 'dop'];

var me = ['dap', 'bun', 'bop'];

Answer ā„–1

Iterate through the given array and check if each item exists in another array called me.

function findCommonElements(arr1, arr2) {
  return arr2.reduce(function (previous, current) {
    if (arr1.indexOf(current) > -1) previous++;
    return previous;
  }, 0);
}

findCommonElements(me, buns); // 2
findCommonElements(me, duns); // 1

Check out the DEMO here

Answer ā„–2

Essential Index Comparison

function checkIndex(a, b) {
    return a.reduce((total, item, i) => {
        if (item !== b[i]) return total + 1;
        return total;
    }, 0);
}

Non-critical Index, Ignoring Duplicates

function compareValues(a, b) {
    return a.reduce((total, item, i) => {
        if (b.indexOf(item) === -1) return total + 1;
        return total;
    }, 0);
}

Disregarding Index, Acknowledging Duplicates

function similarItems(a, b) {
    b = b.slice();
    return a.reduce((total, item, i) => {
        let j = b.indexOf(item);
        if (j === -1) return total + 1;
        b.splice(j, 1);
        return total;
    }, 0);
}

The lower score signifies high similarity, for example:

compareValues(apples, bananas) // 1
compareValues(apples, oranges) // 2
// `bananas` bear more resemblance to `apples` than `oranges`

Keep in mind these operations are not interchangeable when the array lengths differ; checkIndex(a, b) may yield different results compared to checkIndex(b, a) with unequal lengths: a.length !== b.length
For accurate comparisons, ensure the shared array is placed consistently in all tests

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

Tips for utilizing the for each function within a for loop

Looking to showcase prices alongside each product based on their unique sku value, I've put together a price list. An array of data is being iterated through and pushed into the div container. var arr = [ { "sku": "552", "title": "orange", "pric ...

Sending the selected "Id" checkbox data to a Bootstrap Modal and then passing it on to the controller

I have a collection of articles that I need to manage, including the ability to delete specific articles or all articles using a modal popup window. Additionally, my View contains checkboxes for selecting articles. My plan is to retrieve the "Id" of each s ...

How can you leverage Symfony to iterate through a JSON array efficiently?

After selecting a user, I am attempting to display a list of contracts. To achieve this, I have written the following query: /** * @param $firstname * @param $lastname * @return mixed * @throws DBALException */ public function getListPerUser($firs ...

React - Error: Unable to access the 'props' property because it is undefined

I am working on implementing a click event to delete an item from my list, but I keep encountering the error message "TypeError: Cannot read property 'props' of undefined" whenever I click on it. Although I am striving to follow ES6 standards as ...

Issue with Ref when used in a distinct HTML template

I have encountered a frustrating issue with my simple Vue project. When I separate the template and code into individual files, the ref stops working and I end up with an undefined value in the HTML template. This scenario works fine: map.component.vue ...

What methods can I use to prevent multiple calls to isValid in this particular jQuery validation scenario?

I am currently working on validating a field with the following requirements: No validation when the user first lands on the page Validation triggers when the user clicks on the Name Query field, and it validates on both key up and focus out events The f ...

Sending a c# array to a c++ function

Currently, I am working with a CLR class library in c++ that looks like this: namespace ANN_Lib { public ref class ANN_FF_BP { private: int neurons; int inputs; int outputs; double **wi; double *wl; ...

Struggling to showcase API data on React interface

I am working on fetching data from a private API and displaying it on a web page. My frontend is built using React JS, while my backend uses Node with Express and Axios. Everything seems to be working fine until the point where I need to display the fetche ...

Tips for applying an active class to buttons using ng-click?

Here is the HTML code for the buttons. The taskfilter is the filter that controls how the buttons work when clicked and the class name is 'sel' <a class="clear-completed" ng-click="taskfilter = 1" ng-class="{'sel':enabled}"> &l ...

Is there a way to utilize an AXIOS GET response from one component in a different component?

I'm having trouble getting my answer from App.tsx, as I keep getting an error saying data.map is not a function. Can anyone offer some assistance? App.tsx import React, {useState} from 'react'; import axios from "axios"; import {g ...

The AJAX request encountered an unexpected failure that cannot be identified (Using jQuery)

Are you facing issues with a service that returns JSON data? Check out this URL: If you're attempting a simple AJAX request, here's some sample code to get you started: $.ajax({ type: "get", url: "http://api.drag2droid.shamanland.com/ca ...

Error: Undefined object while trying to access 'injection' property

After updating to React 16.x, I encountered the following error: Uncaught TypeError: Cannot read property 'injection' of undefined at injectTapEventPlugin (injectTapEventPlugin.js:23) at eval (index.js:53) at Object.<anonymous> ...

Direct your attention to the cursor problem in Internet Explorer

Here is a snippet of code that automatically changes background images: function changeBackground() { currentBackground++; if(currentBackground > 3) currentBackground = 0; $('body').fadeOut(0, function() { $('body&ap ...

What methods can I use to find all possible combinations from a group of stacks varying in height?

Given: total cost. To Find: all possible combinations of levels that add up to the given cost. Each level in every stack has a unique cost, determined by a function based on a manually entered base cost for level 1. The goal is to determine the combinati ...

What could be causing the decreasing opacity of lines at the edge of my HTML5 canvas?

I have embarked on the journey of creating a bar graph using an HTML5 canvas. The process involves a series of lines drawn with the help of .moveTo(), .lineTo(), and .stroke(). Below is the code snippet I am using for this purpose. Although I am new to wo ...

What is the best way to remove headers and footers programmatically in print pages on Safari using JavaScript?

Struggling with eliminating the header and footer on print pages in Safari using JavaScript? While disabling the header and footer manually can be done through print settings in most browsers, my aim is to automate this process with code to ensure that use ...

Countdown component in Ant Design failing to display correct date

Iā€™m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Losing the properties of a component when employing the 'as' styled-component attribute on an extended styled-component

I created a CallToAction component as follows: const CallToAction = ({ text = "Default text" }) => ( <S_CallToAction>{text}</S_CallToAction> ) const S_CallToAction = styled.div` // Some styles... ` export default CallToAction ...

Discovering the generic type from an optional parameter within a constructor

Looking to implement an optional parameter within a constructor, where the type is automatically determined based on the property's type. However, when no argument is provided, TypeScript defaults to the type "unknown" rather than inferring it as "und ...

augmentable form that can be expanded flexibly

Perhaps I'm missing something really simple here, but I just can't seem to figure this out. I'm attempting to create a form that can dynamically extend. The issue I'm facing is that I can't get this particular code to function: & ...