Discover connections between an Array and an array within Objects

My blog features various articles that users can interact with. Each user has a property called "favorites," which stores an array of their favorite posts. By clicking on the heart icon next to a post, the title of that post gets added to the user's favorites list.

I want to create a section on each user's profile page where they can view all the posts they've added to their favorites. This involves comparing the user's favorites array to the array of all available posts.


userFavoritesArray = ['post1', 'post2', 'post5', ...]
postsArray = [
  { 
    title: 'post1', 
    desc: 'hello'
  },
  ...
]

For example:


user: {
  favorites: ['post1']
}

posts: [
{name: 'post1', desc: 'yo bro'},
{name: 'post2', desc: 'hello im the post2'},
{name: 'post3', desc: 'good morning'}
]

The desired output for this user would be

favorites: [{name: 'post1', desc: 'yo bro'}]

Answer №1

Your inquiry lacks clarity, but I presume you are seeking the following solution:

const input = ['a', 'c']
const database = [
  { title: 'a', foo: 1 },
  { title: 'b', foo: 2 },
  { title: 'c', foo: 3 }
]
const output = mapByTitle(database, input)
console.log(output)
// Result: [ { title: 'a', foo: 1 }, { title: 'c', foo: 3 }]

To achieve this, a combination of Array.prototype.find and Array.prototype.map can be utilized. The former finds an element based on a provided condition, while the latter maps array elements according to a specified callback function.

For instance:

// Implementing `find`:
console.log(database.find(item => item.title === 'a'))
// Result: { title: 'a', foo: 1 }
console.log(database.find(item => item.title === 'z'))
// Result: undefined

// Utilizing `map`:
console.log(['hello', 'world'].map(item => item.toUpperCase() + '!'))
// Result: ['HELLO!', 'WORLD!']

Thus, the function mapByTitle can be constructed as follows:

function mapByTitle (database, input) {
  return input.map(title => database.find(item => item.title === title))
}

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

Retrieve the corresponding data from a separate workbook based on specific criteria

When looking at this specific query here, my task involves comparing the values in wb1.columns(1) to those in another workbook's wb2.columns(1) based on certain conditions. I need to filter Wb2 with the value Close in column 13 M. The main goal ...

Update the value of a table cell with jQuery

I need assistance with changing the value of a td when a specific button is clicked. I have attempted various methods but none seem to be working. Ideally, I want the column to display only USD values when the "Show USD" button is clicked, and display on ...

The AngularJS directive fails to display any content within its element children

Trying to retrieve the innerHTML of the selected node in options The <i class="before"></i> tag should display text from either the selected or the first option when the page loads, within the same group. However, only dropdowns with hardcoded ...

Having trouble with sluggish performance on openbim-components? The OrthoPerspectiveCamera tends to slow down or get stuck when zooming

While using the OrthoPerspectiveCamera in my App (from openbim-components package), I am facing an issue. Whenever I zoom into my model, it automatically switches to FirstPerson mode. This change makes it extremely slow to navigate and zoom in/out of the s ...

Angular 6 and Typescript: How to Map Objects in Arrays within Arrays

We currently have two arrays named speisekarte (consisting of 10 objects) and essensplan (containing 8 objects). const speisekarte = [ { id: 11, name: 'Kabeljaufilet', price: 3.55, type: 'with fish' }, { id: 12, name: 'Spaghet ...

Issue with Jquery focus on dropdown not working

I am facing an issue with setting up the dropdown feature for my list. It's similar to ul li:hover ul li. What I'm trying to achieve is something like ul li:focus ul li in jQuery because I don't think it can be done using CSS. The desired ou ...

Heroku experiences unexpected surge in memory consumption while using Puppeteer

Yesterday, a commit caused the process to hit Heroku's memory limit resulting in an R15 error. The code worked perfectly during testing and on Heroku until it reached a certain number of checked items, triggering the error. What's intriguing is t ...

"Error 404: Issue encountered while trying to save data on Backbone

There seems to be an issue with the /:id portion of my URL; I'm having trouble getting my Mongoose and Backbone ID fields to align correctly. The console is showing this error message: POST http://localhost:8080/api/bears/:id 404 (Not Found) Below is ...

Express Route will respond with a status code of 500 and a generic error message when a file is sent as 'multipart/form-data'

ISSUE DETAILS: I've implemented an express route that accepts files in multipart/formdata format and uploads them to an S3 bucket. To filter image types and temporarily store them on the server, I'm using multer and creating an upload directory. ...

Using JavaScript with namespaces in C#

I am currently trying to explore AJAX and web services through self-teaching using C# and JavaScript. After doing some research on Google, it seems like I might be facing a namespace problem. Here is the snippet of my code: using System; using System.Col ...

Why am I encountering issues accessing a child property in TypeScript?

Here is some TypeScript code that I am working with: export interface SelectQuery_thing { __typename: "ThingQueryPayload"; content: (SelectQuery_thing_content | null)[]; pageInfo: SelectQuery_thing_pageInfo; } export interface SelectQuery_thing_con ...

One issue that may arise is when attempting to use ngOnDestroy in Angular components while rearranging user transitions

Encountered an issue recently with Angular - when the user navigates from component A to component B, component A remains active unless ngOnDestroy is triggered. However, if the user visits component B before going to component A and then leaves, ngOnDes ...

What is the method to display a caret in regular HTML text with the use of JavaScript?

Currently, I am studying JavaScript and aiming to develop a typing game similar to typeracer.com. The goal of the game is to type accurately and quickly without errors. In this game, users input text into a box, and JavaScript then compares their inputs w ...

Issues with sending data through ajax using the post method persist on shared web hosting

I'm facing an issue with Ajax post data. It works fine on localhost but not on shared hosting. Here is my code: <script type="text/javascript> $(document).ready(function(){ $("#login").click(function(){ alert(& ...

Fixing TypeError: Object #<IncomingMessage> has no method 'flash' in ExpressJS version 4.2

Currently, I am utilizing ExpressJS 4.2 and PassportJS for authenticating local users. Everything seems to be working smoothly except for when attempting to display a failureFlash message. Below is my configuration setup, thank you in advance! ==== Necess ...

Incorporating sliding animation into Angular's ng-repeat directive

I am currently working on my code to create multiple divs with a hide button in each one. When the hide button is clicked, I want the corresponding div to fade away and the divs below it to smoothly move up to fill the space left behind. Below is the snip ...

Is it possible for two components to send two distinct props to a single component in a React application?

I recently encountered a scenario where I needed to pass a variable value to a Component that already has props for a different purpose. The challenge here is, can two separate components send different props to the same component? Alternatively, is it po ...

Guide to incorporating animated material icons in vuetify

in Vuetify makes it easy to utilize mainstream material design icons through the use of the v-icon component. An example of this would be: <v-icon>home</v-icon> I am curious if animated material icons are supported and can be integrated in ...

The Select2 choices are not being updated correctly

I am in the process of implementing a feature on my website that allows users to select a Country -> State -> City. The state and city select boxes are initially set to disabled, and when a user chooses a Country, it should display the corresponding ...

Is it possible for a PHP server script to continuously monitor a non-blocking socket?

I am currently working on a project that has two main components. At the moment, I have completed a front end file called View.php (built using HTML5, CSS3, and JQuery) which communicates with the server.php. The server.php file opens a TCP socket connec ...