A guide on sorting an array based on elements from a different array

We are currently in the process of developing an application using Vue and Vuex. Our goal is to display a list of titles for venues that a user is following, based on an array of venue IDs.

For instance:

venues: [
{venue:1, title: Shoreline}
{venue:2, title: Bill Graham}
{venue:3, title: Golden Gate}
{venue:4, title: Orphium}
]

My current list of followed venues includes: [1, 3]

However, I don't want to simply show the IDs 1 and 3. Instead, I want to display "Shoreline" and "Golden Gate" as the followed venues.

I have been attempting to utilize map and filter functions without success.

getFollowingState({ commit, state }) {
  fb.venueFollowersCollection.where("user", "==", state.currentUser.uid).onSnapshot(querySnapshot => {
    let followingArray = []
    querySnapshot.forEach(doc => {
      console.log(doc.data())
      let followed = doc.data().venue
      followingArray.push(followed)
    })
    store.dispatch('getUserVenues', followingArray)
    commit('setFollowedVenues', followingArray)
  })
},

The above code fetches an array of venue IDs that I am following. Here is an example snapshot of doc.data():

email: "greg@..."
name: "Gre..."
phone: "925..."
user: "jxckuJwXxRdgfKmEduYlLbfxd1g1"
venue: "S2XWn8tG0tIMyoOyAcuc"
venueName: "California Memorial Stadium"

Next, my objective is to retrieve each venue object where the ID matches one of the IDs of venues I am following (payload).

getUserVenues({ commit }, payload) {
  fb.venuesCollection.onSnapshot(querySnapshot => {
    let venuesArray = []
    querySnapshot.forEach(doc => {        
      if ((doc.data()).includes(payload)) {
        let venue = doc.data()
        venuesArray.push(venue)
        console.log(doc.data())
      }
    })
    console.log(venuesArray)
    commit("setUserVenues", venuesArray)
  })
},

A challenge arises here because "payload" is not recognized as a string. What adjustments should be made in order to achieve the desired outcome?

Answer №1

A convenient method to filter an array by elements from another array is by utilizing the includes() function:

const locations = [
{location:1, name: 'Beachfront'},
{location:2, name: 'City Center'},
{location:3, name: 'Mountain View'},
{location:4, name: 'Lakeside'}
];

const selectedLocations = [1, 3];

const names = locations
  .filter(item => selectedLocations.includes(item.location))
  .map(item => item.name);

console.log(names);

Output:

[ 'Beachfront', 'Mountain View' ]

Answer №2

It seems like the code you are looking for is something along these lines:

getUserVenues({ commit }, payload) {
  fb.venuesCollection.onSnapshot(querySnapshot => {
    const venuesArray = [];
    querySnapshot.forEach(doc => {
      const venue = doc.data();
      if (payload.includes(venue.venue)) {
        venuesArray.push(venue);
      }
    });
    commit('setUserVenues', venuesArray);
  });
},

You may find the variables a bit confusing because your venue object includes a venue field, rather than an id. Assuming that you are trying to match the id with venue.venue in the payload, using payload.includes should serve your purpose.

If you wish to commit only specific data from the venue object, you can try the following options:

Committing only the names:

commit('setUserVenues', venuesArray.map(v => v.venueName));

Committing both names and ids:

commit('setUserVenues', venuesArray.map(v => ({ id: v.venue, title: v.venueName})));

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

The list countdown for loop only appears in the initial iteration

Hey there, I'm currently facing an issue with duplicating my JavaScript countdowns and displaying images of cards on each loop iteration. Strangely, the countdown only appears in the first instance even though it's within the loop. I'm seeki ...

Guide on extracting unique key values from an array by utilizing a different key

I have an array containing the names of products along with their storage capacities. let products = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storag ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...

Using a variable to store the value of the id attribute in HTML code

How can I dynamically add an ID attribute to an HTML element using a variable declared in JavaScript? Using jQuery var table_row = $('table').find('tr#' + pid); var name = table_row.find('td:nth-child(1)').html(); table_ ...

Go all the way down to see the latest messages

I have developed a messaging system using Vue. The latest messages are displayed from bottom to top. I want to automatically scroll to the end of a conversation when it is clicked and all the messages have been loaded via axios. Conversation Messages Comp ...

Unable to locate module: '@material-ui/pickers' - Material UI React

I encountered an error that said: Material UI React - Module not found: Can't resolve '@material-ui/pickers' in React. Previously, I faced a similar issue with '@date-io/date-fns' but was able to fix it by updating to the latest ...

Recording audio using Cordova and Javascript

Recently, I've been dabbling in creating a new app using Cordova, VueJs, and Onsen UI for VueJs. One of the main features I want to implement is the ability to use the microphone on Android or iOS devices to record audio and then send it to the Google ...

jQuery's Offset().left is experiencing some issues and not functioning correctly

Do you have a question about the jQuery offset() function? On my website, I utilize it to show an "email a friend" window when the email icon is clicked. However, the problem is that the window ends up stuck to the right side of the browser's window ...

Analyzing elements within an array of objects

Here is an array of objects I have: const cart = [ { group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0 { group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1 { group: "group 1", qtd: 18, value: 40, term ...

Does utilizing the i18n module solely for the purpose of translating route names seem excessive?

My coding habit is to write everything in English for easy understanding by developers, but I'm encountering a dilemma while using Nuxt. All the page components I create are named in English, whereas our user base speaks a different language. Should I ...

Leveraging the power of angular's $asyncValidators by implementing a cache

I've created a validation directive that verifies a value against an endpoint App.directive('validate', function(fooService, $q) { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { ...

How can I make rows appear dynamically when the user clicks a button?

I am trying to add rows dynamically when the user clicks on a button. I have created a script for this purpose, but unfortunately, it is not working as expected. Can someone please assist me with fixing it? <script> var i; i = 2; function AddR ...

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Exploring Passportjs Callbacks and parsing arguments

I'm struggling to grasp the concept behind the custom callback in Passport.js. I'm not sure why it requires (req, res, next) at the end. Shouldn't these values be obtained from closure? app.get('/login', function(req, res, next) { ...

Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements. The issue is that in Puppeteer, the onload event is actually triggered automa ...

Is it possible to delete a <div> tag based on screen size using jQuery or JavaScript?

Hello, I was curious if it's possible to dynamically remove a specific div tag using jQuery or JavaScript when the screen reaches a certain size, for example 500px. ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Ways to customize the border color on a Card component using React Material UI

Is there a way to change the border color of a Card component in React Material UI? I attempted using the style property with borderColor: "red" but it did not work. Any suggestions on how to achieve this? ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...