What is the best way to locate the elements in the Array that have these particular IDs

This is a challenging logic problem that I've been struggling with.

For example, I have an array: ["tech", "review", "howto"]. Along with a larger array containing ids and corresponding texts. 👇

[
  { id: "tech", text: "Technology" },
  { id: "fin", text: "Finance" },
  ...
  { id: "review", text: "Product Review" }
]

Using these arrays, I'm aiming to get the following output in JavaScript:

[
  { id: "tech", text: "Technology" },
  { id: "review", text: "Product Review" },
  { id: "howto", text: "How To" }
]

Currently, this is my approach 👇

categorySorter(categories) {
    const categoryState = categorySuggessions.filter(category => category.id === categories.map(category => (category)))
    return categoryState
}

However, this code snippet returns an empty array ([]).

Any suggestions on how to improve this?

I am new to programming and would appreciate any guidance!

Answer â„–1

To filter and find specific elements, you can utilize the combination of filter and includes.

let data = [{ id: "tech", text: "Technology" },{ id: "fin", text: "Finance" },{ id: "digimark", text: "Digital Marketing" },{ id: "coding", text: "Programming" },{ id: "tutorial", text: "Tutorial" },{ id: "howto", text: "How To" },{ id: "writing", text: "Writing" },{ id: "inspire", text: "Inspirational" },{ id: "science", text: "Science" },{ id: "politics", text: "Politics" },{ id: "lifestyle", text: "Lifestyle" },{ id: "food", text: "Food" },{ id: "business", text: "Business" },{ id: "entrepreneur", text: "Entrepreneurs" },{ id: "history", text: "History" },{ id: "health", text: "Health" },{ id: "pet", text: "Pets" },{ id: "parenthood", text: "Parenthood" },{ id: "travel", text: "Travel" },{ id: "india", text: "India" },{ id: "china", text: "China" },{ id: "uk", text: "United Kingdom" },{ id: "us", text: "United States" },{ id: "world", text: "World" },{ id: "news", text: "News" },{ id: "review", text: "Product Review" }]

let idsToInclude = ["tech", "review", "howto"]

let result = data.filter(({id}) => idsToInclude.includes(id))

console.log(result)

Answer â„–2

Almost there! Simply utilize .indexOf to verify if the key is present in your set or not.

const info = [
  { id: "tech", text: "Technology" },
  { id: "fin", text: "Finance" },
  { id: "digimark", text: "Digital Marketing" },
  { id: "coding", text: "Programming" },
  { id: "tutorial", text: "Tutorial" },
  { id: "howto", text: "How To" },
  { id: "writing", text: "Writing" },
  { id: "inspire", text: "Inspirational" },
  { id: "science", text: "Science" },
  { id: "politics", text: "Politics" },
  { id: "lifestyle", text: "Lifestyle" },
  { id: "food", text: "Food" },
  { id: "business", text: "Business" },
  { id: "entrepreneur", text: "Entrepreneurs" },
  { id: "history", text: "History" },
  { id: "health", text: "Health" },
  { id: "pet", text: "Pets" },
  { id: "parenthood", text: "Parenthood" },
  { id: "travel", text: "Travel" },
  { id: "india", text: "India" },
  { id: "china", text: "China" },
  { id: "uk", text: "United Kingdom" },
  { id: "us", text: "United States" },
  { id: "world", text: "World" },
  { id: "news", text: "News" },
  { id: "review", text: "Product Review" }
];

const list = ["tech", "review", "howto"];

const outcome = info.filter(x => list.indexOf(x.id) !== -1);

console.log(outcome);

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

Form a JSON array from a query string in the browser

After querying the geolocation API in the browser, the data retrieved is as follows: browser=opera&sensor=true&wifi=mac:B0-48-7A-99-BD-86|ss:-72|ssid:Baldur WLAN|age:4033|chan:6&wifi=mac:00-24-FE-A7-BA-94|ss:-83|ssid:wlan23-k!17|age:4033|chan: ...

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

Performance Implications: Comparing the Impact of Single Import from Index File versus Multiple Single Imports

Context Currently, I am working on enhancing the performance of my blog built with Gatsby. In addition to performance improvements, I am also looking to implement code-splitting and lazy loading for better user experience. Approaches to Importing Componen ...

What is the most effective method for live-updating a field every 5 seconds in Laravel?

I want to monitor the database to see if a new row is created for each user and display a popup message to notify them. I'm debating between using pusher/socket or making an Ajax call every 5 seconds to achieve this live update without page refresh. I ...

Accessing a file url with Firefox using protractor

I am currently facing a challenge with Protractor as I try to access an HTML file as a website using it. Whenever I attempt to do so, I encounter an error from Protractor stating: Failed: Access to 'file:///C:/filelocation/index.html' from s ...

Issue with React sending a Get request to a Node server using Express

Here is a snippet of code from my React app where I am trying to retrieve data from my database based on a value that is passed. Let's start by examining the section of code that may be causing an issue: Within one of my forms, there is a function th ...

When using jQuery, the function $(this).serialize() will not include input fields that have

Is there a way to serialize and send an entire form using jQuery post, even if only some items have been changed? I want all form fields to be included in the serialization. Here's my HTML: <form name ="XXX" class="user_goal_form"> <input ...

Is it always the case that modifying the props of a child component will trigger a re-render of the parent component, even

I am currently exploring ways to prevent a modal element from re-rendering when it is supposed to be hidden. The tutorial I am following suggests converting the component to a class-based one and using shouldComponentUpdate(). However, I wanted to test if ...

The Efficiency Issue of Angular's setTimeout

Whenever I need to update a component with different input variables, I re-render it every time because there is some specific logic in my ngOnInit() function. To achieve this, I use a method in the parent component where I toggle the showSettings property ...

What is the best way to design a timetable schema in MongoDB specifically for a Teacher Schema?

Greetings to all in the StackOverflow community! I am here seeking some innovative ideas for a project I am currently working on. One of the challenges I'm facing involves storing available days within a Teacher Schema. In this application, a Teacher ...

The modeless service in FeathersJS is failing to provide the correct JSON response

Could someone please explain to me how the service creation process works? I have been struggling for hours trying to receive JSON objects that do not meet my expectations. After much trial and error, I have come up with the following code for the before h ...

What is the process for eliminating transparency from the overlay feature while utilizing Dojox/Standby?

Currently, I'm using a spinner image to indicate loading while retrieving data from the backend. However, the spinner widget creates a translucent overlay over the control. Is there a way to disable this translucency so that only the spinner is visibl ...

Serializing a Map containing key-value pairs represented as a case class using circe

Here is a simplified code snippet that involves a Map with key and value as case classes. The key and value objects are successfully serialized using circe. However, there is a challenge in serializing Map[CaseClassKey, CaseClassValue] with circe. //////de ...

Unable to reset select2 within any function

I am attempting to programmatically add select2. Below is my code snippet: $(document).on("click", "#btnAddRow", function(e) { var newText = $(".rawRow").html(); var lastText = '<div class="row productInfoRow" style="margin-top: 5px;">&apos ...

What is the method for updating the content within a div element?

I am trying to add multiple elements to my content, including an h1 element, an input field, and some buttons. I have written a function to create the h1 and input elements, but when trying to add them to my content div, I encountered an error (TypeError ...

Retrieve the data contained within a displayed embed tag that includes a src attribute

Can anyone provide guidance on how to retrieve the content of an embed tag using src attribute? I have an embed tag pointing to a custom page as src. I tried to use jquery to access the rendered content but I am not getting anything back. Any suggestions ...

Utilizing React Router to dynamically render components based on JSON object data

My current challenge involves rendering React components based on the component names in a JSON file I've created. Specifically, I want to render the TestSection component within the context of my Route component. To achieve this, I am utilizing the ...

Unable to engage with MUI stepper and modify a value

I am hoping to utilize an MUI stepper in place of a Select component. The current Select component is being utilized to signify the status of the document that the user is currently working on (New, In Progress, Complete, etc.). While I have successfully d ...

Verifying changes using Cypress transformations

I'm brand new to using Cypress and I am currently attempting to verify that one of my elements contains a specific style. The element in question looks like this: <div class="myElement" style="transform: translate(0%, 0px); "></div> Her ...

Utilize lodash to eliminate items from an array within an array

I am looking to eliminate users from the removeUser array based on their userName values using lodash. Here is the data I have: {"users":[ {"title":"Mr", "firstName":"John", "lastName":"Doe", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_e ...