Searching for multiple array elements based on their values can be achieved by using various techniques

I am trying to find a way to select multiple elements from an array that share the same value. When I use array.find(), it only returns the first element that matches the condition. For example, in the code below, only "Donald Trump" is displayed in the console:

const data = [
  {
    "position": "president",
    "name": "Donald Trump",
    "language": "english"
  },
  {
    "position": "president",
    "name": "Vladimir Putin",
    "language": "russian"
  },
  {
    "position": "king",
    "name": "Shutruk-Nahhunte",
    "language": "elamite"
  },
];
let result = data.find(elem => elem.position == "president");
console.log(result.name);

However, I need to retrieve all the matching values as an array, like this:

[
  "Donald Trump",
  "Vladimir Putin"
]

Could someone provide guidance on how to achieve this efficiently, especially considering that the actual array is quite large? Thank you for any assistance!

Answer №1

To accomplish this task, I utilize a filter technique.

const info = [
  {
    "position": "president",
    "name": "Donald Trump",
    "language": "english"
  },
  {
    "position": "president",
    "name": "Vladimir Putin",
    "language": "russian"
  },
  {
    "position": "king",
    "name": "Shutruk-Nahhunte",
    "language": "elamite"
  },
];

const filteredArray = info.filter(x=>x.position==='president')
let names = filteredArray.map(x=>x.name)
console.log(names)

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

Sending JSON data along with sendFile() in Node.js and Express done right

After setting up a Node.js server with Express and routing, I am faced with the challenge of passing JSON data onto a specific page ("/users/id") while using sendFile(). While I could make an AJAX request on page load to retrieve the data separately, I am ...

Generate a distinct identifier for the select element ID whenever a new row of data is inserted into a table

Although my title accurately describes my issue, I believe the solutions I have been attempting may not be on the right track. I am relatively new to javascript and web development in general, so please forgive me for any lack of technical terminology. Th ...

Angular: monitoring changes in HTML content within a Component or Directive

I have a situation where I am retrieving HTML content from a REST endpoint using a directive and inserting it into a div element using [innerHTML]. Once this HTML content is rendered, I would like to manipulate it by calling a global function. My approach ...

Unexpectedly, Ajax call is triggering additional callbacks

I am currently facing an issue with my AJAX request in the code below. The Chrome Inspector is showing that the callback function associated with the request is being called twice, resulting in the response being logged into the console twice. Additional ...

Uploading and previewing multiple images on a canvas

After successfully creating single upload for images and placing them on canvas as seen in http://jsfiddle.net/StJnY/, I am now looking to adapt the script for multiple image uploads. Here is how I plan to modify the script: JS : $(function () { $(&a ...

The image remains unchanged in the JavaScript function

My attempt to swap images using jQuery has hit a snag. Upon running the page, it appears that the chase() method finishes executing before the animation has completed. The goal was to create an illusion of chasing between two images by repeatedly replaci ...

Get all the classes from the body element of the AJAX-loaded page and update the body classes on the current page with them

I am currently in the process of AJAX-ing a WordPress theme with a persistent music player. In Wordpress, dynamic classes are used on the <body> tag. The structure I'm working with looks like this: <html> <head> </head> ...

Error: The variable "Set" cannot be found in the react.js code, specifically in Safari browser

An issue has been identified in Safari where a ReferenceError is thrown: "Can't find variable: Set" when using react.js. This error occurs only in Safari, while all other browsers work perfectly fine. The error message points to the main.js file which ...

Having Trouble Accessing Custom Screen in React Navigation?

The navigation from the Order screen to the Home Screen is not working as expected. Every screen in the route works, except for the Home screen, which just navigates back to the Map screen. I have clearly instructed to navigate to Home. Here is the curren ...

What is the reason for my result showing as Object { } rather than MyObj { }?

When utilizing the web development tools console, if a browser object is typed, it will return as "console." > console Console { } > console.log(console) undefined > Console { } This behavior applies to all browser objects. However, when I try ...

JSON.stringify inserts a line break

When using Postman for batch API calls, I need to insert a new line between each record for easy copying and pasting into CSV or Excel. let responses = pm.collectionVariables.get('collectionResponses') if(responses) { responses = JSON.parse(res ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

Uploading files with Ajax in PHP

Illustration of my Ajax script: Script <script type="text/javascript> $(document).ready(function(){ $('.costExcel').on("submit",function(event){ event.preventDefault() var url = "ajax.php"; ...

A guide to creating a JavaScript function that outputs a script in string form

Currently, I am utilizing angular and seeking to add a script to my directive's template. My goal is to create a function that can take the necessary parameters for the script and return it as a string. This approach would prevent me from having to em ...

What is the best method to make the first input field the focus in BootStrap?

Is there a way to prioritize the focus on the initial input element in an HTML form without specifying an ID? How to set the focus to the first input element in an HTML form independent from the id? I'm working with BootStrap and ASP.NET MVC4. De ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

Issues with slow scrolling and sticky sidebar on websites with infinite scrolling feature

My webpage has a sidebar that is supposed to scroll down with the page. However, I am experiencing some lagging issues where the sidebar appears a few seconds after scrolling. Additionally, the sidebar keeps moving downwards, making the page longer and cau ...

Is there a quicker method to access an object's ID?

Within my array of objects, the structure is as follows: var locations = [ [{id: 1, lat: 51.52376322544537, lng: 5.13785702262885, content: 'Title A'}], [{id: 2, lat: 51.52358632767757, lng: 5.137921395645208, content: 'Title B'}], [{i ...

Redux - Refreshing the subtree state

How can I properly reset the subtree of a redux store without resetting the entire store? I want to target only the reducer subtree in question. Check out this example code: //initial state const initialState = { isFetching: false, error: '& ...

JavaScript - utilize regular expressions to check if the argument starts with a forward slash

Currently, I am utilizing nodejs for API testing purposes. To properly test the logic within this if statement, I am in search of a string that aligns with this specific regular expression. if (arg.match(/^\/.*/)) { // ... } Would anyone be able ...