Discover similarities between two arrays

My goal is to compare two arrays and generate a JSON array marking true if there's a match and false if there isn't. The second array will always have values that match some from the first, and it will be smaller as it's derived from the first array.

let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];

The desired JSON array looks like this:

[
  {
    "name": "One",
    "matched": false
  },
  {
    "name": "Two",
    "matched": false
  },
  {
    "name": "Three",
    "matched": true
  },
  {
    "name": "Four",
    "matched": true
  },
  {
    "name": "Five",
    "matched": false
  }
]

Usually, I would use a loop like this:

firstArray.forEach(firstElement=>{
    secondArray.forEach(secondElement=>{
        if(firstArray.indexOf(secondElement)>=0){
            jsonArray.push({'name': secondElement, 'matched': true});
        }else{
            jsonArray.push({'name': secondElement, 'matched': false});
        }
    });
});

However, this method results in duplicate entries in the JSON array where the name matches but the matched value differs.

I feel like I'm overcomplicating something quite straightforward.

Answer №1

To achieve the desired result, you can utilize the map function along with the includes helper.

let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];

jsonArray = firstArray.map(i => {
   return { 'name': i, 'matched': secondArray.includes(i) };
});

console.log(jsonArray);

Answer №2

Many of the solutions provided here involve unnecessary computations, resulting in longer run-times as the array length increases. Test them with arrays exceeding 100k in size for a clear example.

Fortunately, the optimal solution is quite straightforward and operates in O(n):

const firstArray = ["One", "Two", "Three", "Four", "Five"];
const secondArray = ["Three", "Four"];

const map = {};
firstArray.forEach(item => map[item] = false);
secondArray.forEach(item => map[item] === false && (map[item] = true));
const jsonArray = Object.keys(map).map(key => ({ name: key, matched: map[key] }));

Answer №3

Give this a shot:

  const firstArray = ["One", "Two", "Three", "Four", "Five"];
  const secondArray = ["Three", "Four"];
  const jsonArray = [];
  firstArray.forEach(firstElement => {
        if(secondArray.includes(firstElement)){
            jsonArray.push({'name': firstElement, 'matched': true});
        } else {
            jsonArray.push({'name': firstElement, 'matched': false});
        }
 });

Hopefully, this code will do the trick for you

Answer №4

We can utilize the

Array.prototype.includes()

method to verify the presence of an element within an array

let primaryArray = ["One", "Two", "Three", "Four", "Five"];
let secondaryArray = ["Three", "Four"];
let resultArray = [];

primaryArray.forEach(value => {
    if (secondaryArray.includes(value)) {
        resultArray.push({
            'name': value,
            'matched': true
        })

    } else {
        resultArray.push({
            'name': value,
            'matched': false
        })
    }

})

console.log(resultArray);

Answer №5

Utilize the find method to verify if an element exists

firstArray.forEach(secondElement=>{
  let exists = secondArray.find((item) => item === secondElement);
  if(exists){
    jsonArray.push({'name': secondElement, 'matched': true})
  }else{
    jsonArray.push({'name': secondElement, 'matched': false})
  }
});

View Demo

Answer №6

There are two ways to achieve this.

Method 1:

let list1 = ['apple','banana','cherry','date'];

let list2 = ['banana','date'];
let commonList = [];

list1.forEach( item => {
    if(list2.indexOf(item) != -1){
      commonList.push(item);
    }
});

console.log(commonList);   //commonList contains common items

Method 2: Utilize Underscore.js intersection functionality

Start by importing underscore:  
import * as _ from 'underscore';`  

Then use the intersection method to find the common items.  
commonList = _.intersection(list1, list2);

console.log(commonList);   //commonList contains common items

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

Received extra keys from getStaticPaths in NextJs

Currently engrossed in a project for a client using NextJs, The blog section comprises various paths like blog/[:category], blog/[:category]/[:post], and blog/author/[:author]. To achieve this, I am utilizing getStaticPaths and getStaticProps. My approach ...

When trying to install my npm package from the registry, I keep encountering an issue despite being able to install it locally

I recently released my Node.js/typescript package on the npm registry, but I'm encountering issues when trying to install it from there. Oddly enough, local installation works perfectly fine. Here's the output from the local installation: $ npm ...

Is there a delay in using ngShow and ngClick for authentication in AngularJS and Firebase?

Just getting started with AngularJS and encountering an unusual issue with Firebase authentication. The basic setup displays the current user status (logged in or not) along with options to sign in and out. Oddly, when I click the Log-in button for the fi ...

What are the reasons behind the unexpected behavior of the replace() method in the newest Safari update?

What is causing the JS method replace() to behave incorrectly in Safari version 11.1 when using "$<" in the second argument? For example: "aaaXXXbbb".replace(/XXX/, '_before_$<_after_') The actual result is: "aaa$<_after_bbb" The ex ...

Detecting the presence of a mobile keyboard on a website: strategies and techniques

After implementing the code below, I noticed that nothing happens when the keyboard is visible. Despite my efforts to troubleshoot, it seems that window.screen.height remains unchanged. class TestPage extends React.Component { constructor(props) { ...

Clicking the download button will trigger the file to be downloaded every time

Within the documents table, I am iterating through metadata to extract a filename and docid which are then passed to my DocumentDownloadButton component: const DocumentsTableBody = ({ documentMetadata, tableProps }) => { const { Row, Data } = Table ...

Filtering data with AngularJS upon user clicks

Encountering a perplexing issue at the moment. I have created buttons using ng-repeat and my intention is for them to filter my list when clicked on. However, I am facing an issue where the list fails to filter upon clicking. Here are the buttons: <div ...

Reorganize divisions using Bootstrap

I am exploring different ways to manage responsiveness through the reordering of divs. While I am aiming for a solution that is highly flexible, any suggestion would be appreciated. Desktop View: https://i.stack.imgur.com/boSOa.png Mobile View: https:// ...

AngularJS allows users to seamlessly retain any entered form data when redirected, enabling users to pick up right where they left off when returning to the form

I am currently working on a user data collection project that involves filling out multiple forms. Each form has its own dedicated HTML page for personal details, educational details, and more. After entering personal details and clicking next, the data ...

AngularJS - Utilizing Google's Place Autocomplete API Key

Recently, I started digging into Google's APIs and attempting to integrate the Places Autocomplete API with Angular. Although I'm fairly new to autocomplete features in general, I haven't included the jQuery library in my project yet. I&apos ...

What's the best method for efficiently hiding/showing a large number of DOM elements?

Imagine you have a maximum of 100 elements that remain consistent in type and format, but their content changes. These elements are connected to an input field and will update as the user types. What would be the most efficient approach for maximizing per ...

Scrolling to the bottom of the page triggers jQuery to load additional content

Is your jQuery script not working properly when attempting to load more content upon reaching the bottom of the page? It seems to be functional on Safari/iPad and Android Mozilla browsers, but encountering issues on default Android and Chrome browsers. ...

Triggering a dynamically created event with the onchange event

I'm currently working on creating an input type file, and here is the code I have: var element = document.createElement("INPUT"); element.type = "file"; element.id = "element" + i; $("#media").append("<br>"); $("#media").append("<br>"); $ ...

The functionality of tinymce setContent can only be activated by directly clicking on it

Everything is running smoothly with the code below: $('.atitle').on('click', function(){ console.log('323'); tinymce.get("ed").setContent("<p>lorem ipsum</p>"); // it's working ...

Customizing the appearance of React Navigation StackNavigator through background color changes and styling

Recently delving into React Native, I've managed to create a basic app with three different scenes. Initially, I used Navigator for navigation purposes, but found it to be sluggish and decided to give React Navigation (found at https://reactnavigation ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

Somehow, my array only manages to traverse exactly half of its elements

Something odd is happening with my input tag in the HTML file where only half of my array elements are being processed. The input collects numbers/letters and assigns a line of code, like this: let result = Object.fromEntries( Object.entries(answers2).m ...

HTTP 400 Error: Bad Request Callback

I'm attempting to send data using REST API through jQuery AJAX. Here's the code I am using: $.ajax({ url: 'myurl', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(j ...

How about utilizing node.js as a peer for WebRTC?

Are there any available modules for utilizing node.js as a peer in WebRTC? I am interested in using WebRTC in a client/server manner rather than P2P for its ability to send packets unreliably (i.e. avoiding the delay caused by TCP's guarantee of packe ...

Steps on removing a file type from a Material UI textfield

I've been struggling to figure out how to clear a Material UI textfield with type="file" even after trying multiple approaches. My issue arises when I set a file size limit and display an error message if a user tries to upload a file larg ...