Tips for sorting items that possess an array of objects

Can you assist with this issue?

I am trying to filter the items in an array based on certain activities in their object array. Below is the code snippet:

let userArray = [{
    name: "alonso",
    age:16,
    hobbies: [{activity:"videogames", id: 1}, {activity:"watch tv", id:2}]
  },
  {
    name: "aaron",
    age:19,
    hobbies: [{activity:"videogames", id:1}, {activity:"soccer", id:8}]
  },
  {
    name: "Luis",
    age:27,
    hobbies: [{activity:"code", id:3}, {activity:"soccer", id:8}]
}]

If "videogames" is provided as a string, the expected output is:

[{
   name: "alonso",
   age:16,
   hobbies: [{activity:"videogames", id: 1}, {activity:"watch tv", id:2}]
 },
 {
   name: "aaron",
   age:19,
   hobbies: [{activity:"videogames", id:1}, {activity:"soccer", id:8}]
}]

Answer №1

One way to filter an array based on a specific activity is by using Array.prototype.filter() in combination with Array.prototype.some():

const userArray = [{name: 'alonso',age: 16,hobbies: [{ activity: 'videogames', id: 1 },{ activity: 'watch tv', id: 2 },],},{name: 'aaron',age: 19,hobbies: [{ activity: 'videogames', id: 1 },{ activity: 'soccer', id: 8 },],},{name: 'Luis',age: 27,hobbies: [{ activity: 'code', id: 3 },{ activity: 'soccer', id: 8 },],},]

const getUsersByActivity = (array, activity) =>  array.filter(
  user => user.hobbies.some(hobby => activity === hobby.activity)
)

const result = getUsersByActivity(userArray, 'videogames')
console.log(result)

Answer №2

var people = [
{
    name: "aaron",
    age: 19,
    interests: [
      { activity: "videogames", id: 1 },
      { activity: "soccer", id: 8 },
    ],
  },
  {
    name: "Luis",
    age: 27,
    interests: [
      { activity: "code", id: 3 },
      { activity: "soccer", id: 8 },
    ],
  },
];

function findPeopleByInterest(interest) {
  return people.filter((data) => {
    const hobbies = data.interests.map((hobby) => hobby.activity);
    return hobbies.includes(interest);
  });
}

console.log(findPeopleByInterest('videogames'))

Answer №3

By utilizing the array.filter method, you have the ability to selectively remove objects that do not possess the specific trait you desire. For example, this code snippet filters out objects within 'userArray' that do not list "videogames" as their first hobby activity:

userArray.filter(x => x.hobbies[0].activity === "videogames");

Answer №4

filterUsers = userArray.filter(person => {
  if(person.activities.some(activity => activity.type == "videogames")){
    return person
  }
})

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

Setting multiple cookies with the setHeader method in NodeJs is a powerful capability that allows developers

Currently working on a project using node js, and I've encountered an issue with setting two different cookies. Every time I try to set them, the second cookie ends up overwriting the first one. Check out the code snippet below that I'm currently ...

Unique title: "Curved Blocks with Unusual Shapes in SVG Path

Hey there, I'm new to working with SVG and Highcharts. I found a jsfiddle online that I would like to customize for my project, but I've encountered an issue with the rounded corner blocks of lines in the Result panel. Here is the link to the js ...

Utilizing Javascript to work with an xPath XML file that contains namespaces

I've been through a mountain of research and I'm still stuck at a dead-end :( Check out my XML file (test.xml): <bookstore> <book genre="autobiography"> <title>The Autobiography of Benjamin Franklin</title> ...

Ways to ensure the bootstrap table header width aligns perfectly with the body width

I am having an issue with my bootstrap table where the header width is smaller than the body width because I set the table width to auto. How can I align the header and body widths? Here is a link to a plunker showcasing the problem. https://plnkr.co/edit ...

Transferring PHP array data to JavaScript using JSON

Hello there! I'm currently working with a PHP file that uses json_encode to encode an array. This file is then accessed by the jQuery ajax function to fetch the array. However, I'm having trouble understanding how to properly utilize the array. W ...

A solution to determining the size of an array in C++ by using a variable within square brackets

The following code snippet shows my dilemma. I am attempting to declare an array with a size represented by variable n. FILE *fp; fp=fopen("myfile.b", "rb"); if(fp==NULL){ fputs("file error", stderr); exit(1); } int* a; fread(a, 0x1, 0x4, fp); int n=*a; i ...

What is the best way to transfer information from Swift to JavaScript and showcase it in a web view?

I am currently developing an iOS hybrid app using Swift 2 and HTML/JavaScript. My app has a native shell that retrieves information from the calendar and GPS. I want to display this information in my WKWebView and update it every second. The challenge lies ...

Instructions on exporting binary data to a PNG file using nodejs

How can I convert a binary nodejs Buffer object containing bitmap information into an image and save it to a file? Edit: I attempted using the filesystem package as suggested by @herchu, but when I tried the following code: let robot = require("robotjs" ...

The error message states that the object #<MongoClient> does not have the method 'db'

Learning node.js, mongodb, express has been quite challenging for me, especially when it comes to setting up the database. Here is a snippet of my code (app.js): var express = require('express'), app = express(), cons = require('co ...

Cleaning up checkbox names by removing unnecessary characters

I'm having an issue with unnecessary characters in the names of checkboxes. There is a certain line var string = "<div class="blblb"><input type="checkbox" name="dasdasads"><input type="checbox" name="adsdsada"></div>"; The ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Error encountered while trying to access JSON information

I received some JSON data: const randomData = [ { gender: 'male', name: { title: 'Mr', first: 'Blake', last: 'Li', }, }, ]; However, when I ...

How can I replicate the vlookup function using my indexOf method?

When trying to locate a specific word in Excel similar to <lookup>, I aim to design a form for users to input data they are looking for and then display the corresponding description. However, I am facing a challenge in writing the script. I have w ...

Leveraging jQuery to manipulate an SVG file

jQuery is designed to work within HTML pages that contain JavaScript code. While SVG and HTML both use the same DOM Level 2, SVG is XML-based and employs ECMAScript. What potential issues could arise from utilizing jQuery with SVG? Is it more advisable t ...

Working with Ember.js to manage relationships using a select element (dropdown) for create/edit operations

I'm trying to establish a relationship through a dropdown in my Ember application. Here is my Books model: import DS from 'ember-data'; export default DS.Model.extend({ // Relationships author: DS.belongsTo('author'), name ...

Server has sent an Ajax response which needs to be inserted into a div

I have a modal window that sends a POST request to the server. Before returning to the view, I store some information in ViewData. Here's an example of what I'm doing: ViewData["Msg"] = "<div id=\"msgResponse\" class=\"success ...

Encountering UnhandledPromiseRejectionWarning even after implementing thorough rejection handling techniques

Although I have found solutions on Stack Overflow for issues related to UnhandledPromiseRejectionWarning, none of them seem to address my specific case. I thought I knew how to handle promises, but this particular scenario is baffling me. Can someone pleas ...

Creating elements in Polymer 2.0 is a breeze. Simply use the `createElement` method, then seamlessly import it using `Polymer

While working on a project, I encountered an issue where I was creating and importing an element while setting attributes with data. The code should only execute if the element hasn't been imported or created previously. However, each time I called th ...

Tips for keeping a login session active on multiple tabs

As I am in the process of developing a website, one issue I am facing is determining the most effective method to maintain user login sessions. Currently, I am utilizing Html5 web storage known as "session storage" to keep track of whether a user is logged ...

Resolver for nested TypeORM Apollo queries

I've set up a schema that includes database tables and entity classes as shown below: type User { id: Int! phoneNumber: String! } type Event { id: Int! host: User } Now, I'm attempting to create a query using Apollo like this ...