Verify whether the elements of the first array are present in the second array, and display the results

Verify whether the second array includes the elements from the first array and display them, otherwise show the elements from the second array that are not in the first one.

var contacts = [{name:'muzz',no:1},{name:'muzamil',no:2},{name:'hamza',no:3}]

var recipient = ['2','4']

function check () {
   contacts.forEach(({name,no}) => {
          if(recipient.includes(no.toString())){
           console.log('exists',name)
          } 
        else {
            recipient.forEach(e =>{
                if(!recipient.includes(no.toString()) && contacts == no){
                    console.log(e);

                }
            })
       }
   })
}

Please point out any errors in my code. The 'else' block seems to be iterating through all elements again unnecessarily.

Answer №1

Is this the solution you are looking for?

function mapContactsToRecipients (contacts, recipients) {
    const contactsMap = contacts.reduce((acc, {no}, i) => (acc[no] = contacts[i], acc), {})
    return recipients.reduce((acc, el) => (acc.push(contactsMap[el]?.name ?? el), acc), [])
}

var contactsList = [{name:'muzz',no:1},{name:'muzamil',no:2},{name:'hamza',no:3}]
var recipientList = ['2','4']
const resolvedContacts = mapContactsToRecipients(contactsList, recipientList)
console.log(resolvedContacts)

Answer №2

To start, iterate through the recipient array and then search for a matching object in the contacts array by comparing it with the current recipient:

var contacts = [{name:'john',no:1},{name:'jane',no:2},{name:'bob',no:3}]

var recipient = ['2','4']

function findMatch () {
  recipient.forEach(r => {
    var match = contacts.filter(c => c.no == r);
    if(match.length){
      console.log('Found a match:', match[0].name)
    } 
    else {
      console.log('No match found for:', r);
    }
  });
}
findMatch();

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

Why does my event dispatch only run once upon form submission in Svelte JS?

My code successfully fetches data and puts it in a card when new data is added to the input. However, the issue arises when more than one data entry is made - although the data gets added to the database, it does not reflect in the data list. Can anyone he ...

Having trouble with my code trying to transfer elements back and forth between two unordered lists using an "addEventListener"

I have developed a task management system where users can create a to-do list for their daily tasks. Upon completion of a task, they can tick the checkbox next to it, which will trigger a strikethrough effect. The completed tasks are then moved from the "u ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

KineticJS: Issue with JSON saving - Objects are being duplicated during the save process

Major Revision After assessing my current situation, it appears to be another puzzle or scenario, specifically related to saving to json in a broader context. To illustrate, I include a new Shapegroup to a layer on the stage by utilizing the following co ...

Switching videos upon clicking buttons

Hey there! I've got an interesting challenge for you. I have four mp4 videos featuring a cartoon character performing various emotes. My goal is to create a toggle switch that, when activated, will display the first video (intro) along with three butt ...

Using JSON.stringify to format data and making an asynchronous $http request

I am working with a JavaScript string that looks like this: user_fav = "21,16"; I need to process this string through a function so that it becomes a JSON array with an id key, like this: {"id":21},{"id":16} This JSON array is then used in an $http req ...

Troubleshooting Mongoose and MongoDb Connectivity Issues

Previously, I had no trouble connecting to Atlas from my home wifi, but I encountered issues at Starbucks. After switching to google fiber, I am now facing this error. at Pool.<anonymous> (/Users/j/Desktop/projects/templateApp/node_modules/mong ...

Displaying elements upon clicking using Javascript

I am in the process of achieving this task without Jquery. My goal is to display a div when triggering an event. Currently, I have the following code to hide the element: document.getElementById('element').style.display = 'none'; Her ...

"Owlcarousel Slider: A beautiful way to showcase

Currently, I am working on a project that involves implementing a slider. Since I lack expertise in JavaScript, I opted to use a plugin called owlcarousel. The challenge I'm encountering relates to the sizing of the container for the items. I'm ...

Frontend not displaying errors despite using express-validator

Currently experimenting with nodejs, I have passportjs configured and trying to implement validation for the register form. Here is my current setup, route // Register :post router.post('/dashboard/register', body('firstname').notEmpt ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

How to use jQuery to gather all the text from a textarea

Is there a way to automatically select all text inside a textarea when it is clicked on? Additionally, can this selection be deselected by clicking again? ...

Exclude files from all folders except one in gulp source

This is the structure of my folders: views | - core | | | -core.module.js | core.controller.js | some.js | - home | -home.module.js home.controller.js somemore.js ... ... In my gulp file, I am looking to include all js files from the views ...

Repetitive data in a list with AngularJS

There's probably a simple solution to this: I have some data in a controller, and depending on whether an item is selected or not, it should display different HTML. If the item is selected, the HTML should be: <li> <a href="#"><s ...

Implementing a delegator with ExtJS 4.1: A step-by-step guide

As a newcomer to javascript, I've recently been tasked with maintaining an application built in Sencha ExtJS 4. One of the components I need to modify is a tooltip feature that displays information when hovering over certain elements. This tooltip app ...

Gutenberg NPM remains in its original state without any alterations

I experienced some issues with the NPM when making changes in blocks or other elements as the changes were not working properly. Below is my gutenberg.php file: function MyBlocks() { wp_register_script('blocks-js', get_template_directory_ ...

Issue with material-ui-dropzone, the DropzoneAreaBase component not displaying the preview of the uploaded files

Has anyone encountered issues with the DropzoneAreaBase component from the material-ui-dropzone library? I am having trouble getting it to display added file previews. Any insights into why this might be happening? <DropzoneAreaBase onAdd={(fileObjs) ...

Differences between Angular 4 and AngularJs directives

Delving into the world of Angular 4, I have encountered a slight hurdle in my understanding of directives. My goal is to create a directive that can resize an element based on its width. Back in the days of AngularJs, this task was accomplished with code r ...

What are some tips for leveraging Next.js server-side rendering when utilizing React hooks extensively?

Lately, I've delved into a frontend project utilizing Next.js and I'm on the quest to maximize the benefits of its SSR capabilities. While looking to incorporate client-side fetching as well, I stumbled upon some insights regarding React hooks wi ...

Failure to trigger Bootstrap modal upon button activation

I am currently working on developing a basic student list webpage using bootstrap. My goal is to create a modal that pops up when the user clicks a button, allowing them to enter the required details. However, before implementing this feature, I decided to ...