Display the object that matches all strings in an array in JavaScript

I need help displaying matching countries based on the codes provided in the returned array below.

Returned Array:

["USA", "FRA", "GBR"]

List of Countries:

export const COUNTRY_CODES = [
  {
    country: "United States of America",
    code: "USA",
  },
  {
    country: "Albania",
    code: "ALB",
  },
  {
    country: "France",
    code: "FRA",
  },
....
]

The desired Output should display the names of the matching countries:

["United States of America", "France"]

Javascript Code:

const flatArr = ["USA", "FRA", "GBR"]
COUNTRY_CODES.find((v) => flatArr === v.country)

Answer №1

One effective approach to accomplish this task is by utilizing the reduce method in combination with includes.

const COUNTRY_CODES = [
  {
    country: "United States of America",
    code: "USA",
  },
  {
    country: "Albania",
    code: "ALB",
  },
  {
    country: "Algeria",
    code: "DZA",
  },
  {
    country: "France",
    code: "FRA",
  },
];

const flatArr = ["USA", "FRA", "GBR"];

const matchedCountries = COUNTRY_CODES.reduce((matched, countryCode) => {
  if (flatArr.includes(countryCode.code)) {
    matched.push(countryCode.country);
  }

  return matched;
}, []);

console.log(matchedCountries); // ["United States of America", "France"]

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

Creating a restriction for executing a function only once per user in JavaScript with React

I am working on implementing a like button feature for reviews, where users can like a review but are restricted from liking the same review more than once. const handleHelpfulButtonClick = () => { console.log(review) props.dispatch(incrementi ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

What is the best way to erase data from my input field that already contains a value?

There is an input field that is filled with data retrieved from an API and saved in the Redux state: state = { popoverScenarioName: null, } scenarioNameChange = (e) => ( this.setState({popoverScenarioName: e.target.value}) ) // .... <StyledIn ...

Can the .scroll function be turned off when a user clicks on an anchor link that causes the page to scroll?

I am currently developing a timeline page and I want to implement a feature similar to the chronological list of years displayed on the right side of this webpage: As part of this feature, I have set up a click event which adds a circle border around the ...

I'm interested in learning the best way to insert the images from this JSON file into the corresponding div elements

I have completed developing a clone of an Instagram web page. Although I can retrieve data from the JSON file and insert it into the <img> tag, I am facing difficulty in displaying each image above its respective .below-image div with consistent spac ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

What is the process for bringing an array from a .js file into an HTML document?

Exploring the world of JS and HTML, I recently came across an assignment that involved working with a file named stocks.js, which houses an array of stock information: 'use strict'; const stocks = [ { company: 'Splunk', symbol: &ap ...

Can the onchange event be utilized for saving an array?

My attempt to use a state array and onchange event to track input entries resulted in the array continuously elongating without updating the existing elements. Instead, new elements were being created every time I added something. Here is my code snippet: ...

Strengthening JavaScript Security

Throughout the past few years, I have delved into various javascript libraries like Raphael.js and D3, experimenting with animations sourced from different corners of the internet for my own learning. I've obtained code snippets from Git repositories ...

Sorting a collection based on an array value in Meteor JS

I'm currently facing the challenge of sorting a collection based on a specific value while another value is equal to something else. Please refer to the document below: { "_id": "zLFp8KptxzACGtAZj", "createdAt": "2015-05-28T21:11:57.044Z", ... ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

Upon clicking the "show more information" button on the page, JavaScript executes the function to display additional details

<a href="#" class="button">Read More</a><br> I'm currently struggling with programming a button on my website. Specifically, I need the Read More button to display all information related to the CDs I have for sale when clicked. A ...

The Bootstrap 4 tooltip is failing to display correctly and is only functional for anchor tags

Utilizing bootstrap 4, I aim to display tooltips on both buttons and anchor tags. However, the tooltips only appear on anchor tags and not on buttons. Furthermore, even when the tooltip does display, it lacks proper styling and appears white without adheri ...

Create a "Line" on the canvas by adjusting the attributes of the "Line" object using Three.JS

I have successfully created a cube and lines using Three.js. My goal is to position the lines around the cube as guidelines, as shown below: However, I am struggling to understand the properties of the line: var lengthVertArray = lengthLineGeometry.vert ...

Table expands to full width

I am facing an issue with a table that has a large number of elements. I would like the table to expand to the full width of the screen, but it slows down significantly when it does so. https://i.sstatic.net/s475I.png However, I have noticed that if I se ...

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...

Rearrange the positions on the circle

I created a setup where I've arranged multiple items around a camera in a circular manner, and currently they are positioned in a counter-clockwise direction using the following code: answer.position.y = Math.sin(answerBoxRadians) * circleRadius; an ...

Is there a way to limit the rotation of an a-camera in aframe?

One scenario could be enabling rotation around the z-axis within a range of -70 to 70 degrees, or alternatively, preventing rotation around any arbitrary axis. Thank you! ...

Tips for passing an object by value to an Angular2+ component

Imagine having a scenario where I create a component that takes a Foo instance and generates a form for editing. export class ChildComponent implements OnInit { @Input() foo : Foo; @Output() onChange : EventEmitter<Foo> = new EvenEmitter<Foo& ...

Embedding JavaScript Triggering a 500 Internal Server Web Error

Scenario I am looking to provide bike rental companies (shops) with the ability to redirect customers to an online reservation system on my platform. This will allow them to offer bike reservations specific to their shop only. Current Progress To start, I ...