Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code:

var teams = [
  { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] }, 
  { name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] }, 
  { name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }
];

My goal is to filter based on a search query, for example if I search for m5, I want my result to look like this:

var teams = [
  { name: 'Team1', members: [] }, 
  { name: 'Team2', members: [{ name: 'm5' }] }, 
  { name: 'Team3', members: [] }
];

To achieve this, I have properties teams and filteredTeams, and in my search function I am doing the following:

onSearchChange(event: any): void {
  let value = event.target.value;
  this.filteredTeams = this.teams.map(t => {
    t.members = t.members.filter(d => d.name.toLowerCase().includes(value));
    return t;
  })
}

While this approach works partially, it replaces the members array on each call which is not ideal. I understand the issue here, but I'm unsure about the best way to implement this filter. Any suggestions?

Answer №1

your approach was almost correct, but the mistake you made was altering the original objects in the teams array.

To fix this issue, you can utilize the spread operator to create a new entry and then generate an entirely new array with updated values.

const teams = [
  { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] }, 
  { name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] }, 
  { name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }
];

const value = 'm5';

const result = teams.map(t => {
  const members = t.members.filter(d => d.name.toLowerCase().includes(value));
  return { ...t, members };
})

console.log(result)

Answer №2

Give this a try. Instead of using a set value like m5, input your own.

const teams = [
  { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] }, 
  { name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] }, 
  { name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }
];

const filteredTeams = teams.map(team => ({ name: team.name, members: team.members.filter(member => member.name.includes('m5')) }));

console.log(filteredTeams);

Answer №3

Instead of mutating the original objects, consider assigning new properties to the result object for mapping purposes.

var teams = [{ name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] }, { name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] }, { name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }],
    result = teams.map(o => Object.assign(
        {},
        o,
        { members: o.members.filter(({ name }) => name === 'm5') }
    ));
    
console.log(result);
console.log(teams);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

To enhance your search functionality, it's a good idea to refactor your filter function like this:

const customFilterFunction = (data, filters) => {
    const filteredValues = filters.map(filter => filter.toLowerCase());
    
    return data.map(item => ({
        ...item,
        values: item.values.filter(value => filteredValues.includes(value.name))
    }))
};
// -----

updateSearch(event: any): void {
    let inputValue = event.target.value;
    this.filteredData = customFilterFunction(this.data, [inputValue]);
}

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

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

Embeddable javascript code can be enhanced by incorporating references into the header

I have developed a basic calculator application using HTML, JavaScript, JQuery, and CSS. My intention is to allow others to embed this calculator app on their own web pages by utilizing a file named generate.js. Within this file, there are several documen ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

What is the method for populating a dropdown using ajax in the Jade template engine?

Looking to dynamically populate a dropdown based on the selection of another dropdown. Here's the code snippet: script. var b_name = []; function jsFunction() { var client = document.getElementById('drop_client'); var c_name = cli ...

Experiencing issues in retrieving data post-login using ASP.net session key method

I have developed a website using AngularJS for the front-end and Windows webforms for the back-end. I believe that the Authorization process is carried out using ASP.net Session Key. The approach involves creating an AngularJS Post method for "login" foll ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

Is it possible to showcase a variety of values in mat-select?

Is it possible to pass different values to the .ts file in each function? For example, can I emit a String with (selectionChange)="onChangeLogr($event)" and an object with (onSelectionChange)="onChangeLogr_($event)"? How would I go about doing this? ...

toggle visibility on click using Angular

Within my Angular application, there is a plus button: <div style="display:inline-block;text-align:left;margin-bottom:2vh;" class="col-md-10 col-md-offset-2"> <button type="button" class="btn btn-default" (click)="MoreSentences(result.w ...

Tips for incorporating Javascript in an innerHTML inline css situation

I'm just starting to learn about html5 and php. I'm curious about how to incorporate javascript into my existing code. Currently, I have data from a database displayed in an HTML table. My goal is to align the output of the last cell more toward ...

Ways to create a scrollable div with the help of Javascript

I am currently developing a web app on the Tizen platform. Within my HTML5 code, I have a div element with an image set as its background. In certain scenarios, I need to display random text within this div multiple times. The text can vary in size and ma ...

How can I properly include DefinitelyTyped TypeScript definition files in a .NET Core project?

Previously, under asp.net for .net framework, I utilized NuGet to incorporate TypeScript type definitions from third-party libraries (*.d.ts files) provided by DefinitelyTyped. However, with the shift to .NET Core, it seems that NuGet is no longer recommen ...

I encountered an error in my Rails 4 project where I got a NoMethodError stating "undefined method `id' for nil:NilClass" in my create.js

When I click a button, I'm attempting to display a partial. It seems like I am making an obvious mistake... and I suspect it's not related to the following code snippet: $('#modrequest').empty(); $('#modrequest').html("<%= ...

Exploring the use of v-model in Vue3 child components

After some exploration, I recently discovered that in Vue3, the v-model functionality does not work responsively or reactively with child Component. The following code snippet showcases how the username data gets updated: <template> <div> ...

Pass RGBA color code from JavaScript to Laravel controller

I have an exciting project where users need to select a color value in hex format. Once I retrieve this value in JavaScript, I convert it to Rgba format. Now, my challenge is figuring out how to send this converted value to the controller for database stor ...

Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds: var item = 'apple'; if(document.body.innerHTML.toString().indexOf(item ...

Javascript and CSS combo for creating a stylish fade effect

Hey everyone, I have a design challenge where I need to change the color of a picture inside a box when the user hovers over it. I have four boxes like this and my goal is to make everything else fade out when a user hovers over a specific box. Anyone kn ...

Using the Coinbase.com API with HMAC authentication in a Node.js environment

I recently delved into some node.js documentation, specifically crypto and https, in an attempt to utilize the coinbase.com API within my coin.js file to retrieve the bitcoin balance of my account. However, I am encountering errors. Upon running the code w ...

Unable to delete React element by ID as it is undefined

Having some trouble deleting an item by ID with React. Despite the backend routes functioning properly (node and postgresql), every attempt to delete an item results in it reappearing upon page refresh. The command line indicates that the item being delete ...

Ways to create a sequential appearance of elements through CSS animations

Can you help me achieve a wave effect for elements appearing one by one using CSS animation (jQuery)? Currently, all the elements show up at once and I want to create a wave-like motion. Any assistance would be greatly appreciated. $(window ...