Determine if two sets of arrays have the same identification numbers

Initially, my arrays are named after the different continents of the world.

europe= [];
northAmerica = [];
southAmerica = [];
asia = [];

In addition to these, I also have two arrays containing some specific data.

arr1 = [1,3];

arr2 = [
  { country: "Brazil", id: 1, continent: "southAmerica" },
  { country: "Germany", id: 2, continent: "europe" },
  { country: "India", id: 3, continent: "asia" },
  { country: "China", id: 4, continent: "asia" },
];

My objective is to match IDs from both arrays and then push the corresponding country name into the respective continent array.

This was my initial attempt:

arr2.map((item) => {
        if (arr1.find((id) => id === item.id)) {
          if (item.continent === "southAmerica") {
            southAmerica.push(item.country);
          }
          if (item.continent === "asia") {
            asia.push(item.country);
          }
        }
      });

Unfortunately, only the last value matches and gets pushed into the arrays.

Answer №1

Follow this approach.

const continents = {
  europe: [],
  northAmerica: [],
  southAmerica: [],
  asia: []
};


arr1 = [1, 3];

arr2 = [
  { country: "Brazil", id: 1, continent: "southAmerica" },
  { country: "Germany", id: 2, continent: "europe" },
  { country: "India", id: 3, continent: "asia" },
  { country: "China", id: 4, continent: "asia" },
];

arr1.forEach(_id => {
  arr2.find(obj => {
    if (obj.id === _id) {
      continents[obj.continent].push(obj.country);
      return;
    }
  });
});

console.log(continents);

Answer №2

To simplify accessing arrays, consider using an object along with forEach and includes methods.

const continents = {
  europe: [],
  northAmerica: [],
  southAmerica: [],
  asia: [],
};

const arr1 = [1,3];

const arr2 = [
  { country: "Brazil", id: 1, continent: "southAmerica" },
  { country: "Germany", id: 2, continent: "europe" },
  { country: "India", id: 3, continent: "asia" },
  { country: "China", id: 4, continent: "asia" },
];

arr2.forEach(data => {
  if (arr1.includes(data.id)) {
    continents[data.continent].push(data.country);
  }
});

console.log(continents);

Another method is to use reduce

const arr1 = [1,3];

const arr2 = [
  { country: "Brazil", id: 1, continent: "southAmerica" },
  { country: "Germany", id: 2, continent: "europe" },
  { country: "India", id: 3, continent: "asia" },
  { country: "China", id: 4, continent: "asia" },
];

const continents = arr2.reduce((continents, data) => {
  if (arr1.includes(data.id)) {
    continents[data.continent].push(data.country);
  }
  return continents;
}, {
  europe: [],
  northAmerica: [],
  southAmerica: [],
  asia: []
});

console.log(continents);

Answer №3

const arr1Set = new Set(arr1);
let countriesWithIdenticalIds = []
// Find objects in arr2 that have IDs present in arr1
const checkForIdenticalIds = arr2.some(obj => {
    if (arr1Set.has(obj.id)) {
        countriesWithIdenticalIds.push(obj.country)
    }
});


console.log(countriesWithIdenticalIds); // Output: true

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

What is the best way to link a CSS file within a PHP document's head section and a JavaScript file just before the closing body tag?

How can I properly include a CSS file in the head section of a PHP file? Currently, I am including CSS like this: <?php include('./includes.header.html'); ?> <style><?php include('./test.css'); ?> </style> The ...

Deleting items from the DOM using JavaScript

I am retrieving all the list elements from a menu in order to eliminate the ones that I do not want. let prodMenu = document.getElementsByClassName("productMenu-category"); for (let i = 0; i < prodMenu.length; i++) { if(i > 0 && ...

Testing the Postman Scripts: Analyzing the data within the response JSON

Hey there, it's PostMan 6.0.10! I've been diving into test scripts and could use some help in understanding how to query and examine JSON responses more effectively. Even after going through the excellent documentation, I still have a bit of conf ...

Locating the source of the function call within a file in Node.js

Is it possible to determine the location of a file if a method from a module is called within that file? For example: // my-module.js module.exports = { method: function () { // I would like to know the path to my-app.js here } } // my-other-mod ...

Giving numerous divs identical attributes

Currently working on developing a social media platform similar to Instagram. Encountered an issue while implementing the story feature. Upon opening the story, I created lines using div elements with a common class for CSS styling purposes. However, I int ...

The scene is filled with meshes, but all that can be seen is the renderer's clear color

I am currently experimenting with Three.js and jQuery to develop a small visual application. My main objective is to display all the meshes I have on the screen. The Issue: Unfortunately, none of the meshes are visible on the screen at all. Observations: ...

I have a jQuery slider for changing font sizes that won't go away, but I could use some assistance converting it to Vanilla

I currently have a font resizing slider implemented in Jquery, but I am looking to convert it into vanilla JavaScript. Although the Jquery version is functioning correctly, I am struggling with translating it into plain JavaScript. Here is my code: <!D ...

"Exploring the contrast between local minimum and maximum values with Numpy in Python

I'm currently working on a function to find the maximum dip in numpy arrays A, B, C, D and obtain the Expected Result. Taking array C as an example with values of 0,10,11,-23,, it shows a drop from 0 to -23, resulting in a total drawdown of -33. How c ...

Tips for using Object Dot Keys and Array Dot Map to showcase data within a component

Currently, I am working with a React Component to display data by utilizing the Object.keys() method and then attempting to iterate through the data using .map(). This is how my data is being printed out by redux-logger: body: {data: [0: { attributes: ...

Save picture in localStorage

Hello, I am currently working on a page where I need to retrieve an image from a JSON file and store it locally. Below is the code I have been using: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min. ...

Having trouble passing data between view controllers

In my AngularJS application, I have a table column in main.html that is clickable. When clicked, it should redirect to a new customer page with the value of the column cell as the customer's name. There is a corresponding service defined for the app m ...

Enhance Your Website with a jQuery Plugin for Dynamic Updates to ElementsgetPost

Is there a way to update the content inside an element by passing a new value to the public method updateText? Currently, when I try to pass a new string to the updateText method and click the button, only the method name is received as an argument instea ...

Help needed understanding the instructions from my teacher regarding the utilization of multidimensional arrays in C++

I am currently tackling a programming project for my course that involves creating a shape that can be manipulated using the mouse. I am utilizing eclipse on an oracle VM running Linux Mint. As part of the assignment, my professor provided some guidance in ...

Issue with installing vscode-ripgrep during VSCode build/run process

After attempting to build and run VSCode on my Ubuntu 17.10 by following the instructions from this guide: https://github.com/Microsoft/vscode/wiki/How-to-Contribute#build-and-run, I encountered an issue when installing dependencies using yarn. The error m ...

Ways to transform the DropBox chooser button into an image

I'm looking to incorporate an image in place of Dropbox's default chooser button. Despite reviewing their API documentation, I haven't come across any methods to use alternative elements for the Dropbox chooser. Does anyone have a solution f ...

Trouble receiving JSON data from jQuery method

I am encountering difficulty in correctly capturing a JSON object within a function that is executed when the page loads. My goal is to capture this object so that I can later POST it to another page based on user action. This code is being run on Windows ...

AngularJS - where each client maintains their own MongoDB database

After spending hours on this task, I'm still struggling to find a solution. I have a mean stack application that caters to multiple clients, and I am looking to assign each client their own database. Is this possible? For Example var client_name = ...

Ensuring radio button validation prior to redirecting to contact form

I created a survey form using HTML and CSS. I am looking to add validation to the questions before redirecting to the Contact form page. Currently, when a user clicks on the submit button in the Survey form, the page redirects to the contact form. Howeve ...

Iterate through the .json file and add markers to a leaflet map

Apologies for the basic question, but I'm struggling with understanding JavaScript and json files. I have a .json file that updates server object locations every 5 seconds, and I want to plot these coordinates on a map using leaflet for staff access. ...

How to retrieve JSON data from ASP.NET code-behind file and pass it to JavaScript

I'm facing an issue with my webstatic method that converts my dataset into JSON. I want to retrieve this JSON in my JavaScript file, but unfortunately nothing is appearing in my div. As a newcomer to ASP.NET and JSON, I must be doing something wrong h ...