Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if two arrays contain identical ids

By default, I have arrays with the name of the continents.

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

And i have two arrays with some 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" },
];

If the id matches in the arrays, I need to send the string obj.country to the corresponding array of the continent.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried like this:

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);
          }
        }
      });

But only the last value is sent to the arrays.

>Solution :

Do it like this.

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading