Utilize the objects array property to filter an array of objects

Struggling to wrap my head around this, not sure if it's feasible in this manner but I just can't seem to grasp it.

I have an array of objects where each object contains some values and another array of objects. Essentially, I need to filter the main array and remove a single object from the events array.

Below is the data array:

let data = [
  {
    id: 1,
    date: '2023-10-01',
    events: [{ id: '1a', name: 'event 1' }, { id: '1b', name: 'event 2' }],
  },
  {
    id: 2,
    date: '2023-10-02',
    events: [{ id: '2a', name: 'event 1' }, { id: '2b', name: 'event 2' }],
  },
  {
    id: 3,
    date: '2023-10-03',
    events: [{ id: '3a', name: 'event 1' },{ id: '3b', name: 'event 2' }],
  },
];

An example of what I want to achieve is to filter the data so that if the id == 1, then remove event with name `event 1`.

let data = [
  {
    id: 1,
    date: '2023-10-01',
    events: [{ id: '1a', name: 'event 1'}],
  },
  {
    id: 2,
    date: '2023-10-02',
    events: [{ id: '2a', name: 'event 1' }, { id: '2b', name: 'event 2' }],
  },
  {
    id: 3,
    date: '2023-10-03',
    events: [{ id: '3a', name: 'event 1' },{ id: '3b', name: 'event 2' }],
  },
];

Here's what I've attempted so far, but struggling to make it work:

console.log(data.filter((item) => item.id !== '1')[0].events.filter((event) => event.id != '1b'))

I also tried filtering then filtering again, but no luck so far:

const filtered = (data.filter((item) => item.id == '1'))
console.log(filtered.filter((event) => event.id == '1a'))

Any suggestions or help would be appreciated. Thank you!

Answer №1

If you are looking to generate a fresh array without altering any existing arrays, follow these steps:

const data = [{id: 1,date: '2023-10-01',events: [{ id: '1a', name: 'event 1' }, { id: '1b', name: 'event 2' }],},{id: 2,date: '2023-10-02',events: [{ id: '2a', name: 'event 1' }, { id: '2b', name: 'event 2' }],},{id: 3,date: '2023-10-03',events: [{ id: '3a', name: 'event 1' },{ id: '3b', name: 'event 2' }],},];

const result = data.map(obj =>
    obj.id !== 1 ? obj : {
        ...obj, 
        events: obj.events.filter(({name}) => 
            name === 'event 1'
        )
    }
);

console.log(result);
                 

Answer №2

You're not seeking to directly filter the data itself. Your goal is to iterate through the data and, when a specific condition is satisfied on an object within that iteration, selectively filter a property of that object.

For instance:

let data = [
  {
    id: 1,
    date: '2023-10-01',
    events: [{ id: '1a', name: 'event 1' }, { id: '1b', name: 'event 2' }],
  },
  {
    id: 2,
    date: '2023-10-02',
    events: [{ id: '2a', name: 'event 1' }, { id: '2b', name: 'event 2' }],
  },
  {
    id: 3,
    date: '2023-10-03',
    events: [{ id: '3a', name: 'event 1' },{ id: '3b', name: 'event 2' }],
  },
];

data.forEach(d => {                                        // iterating over data
  if (d.id === 1) {                                        // checking if condition is met
    d.events = d.events.filter(e => e.name === 'event 1'); // filtering events
  }
});

console.log(data);

Answer №3

If we consider the second array to be structured like this:

const ev_data = [{id:1,event_name:'event 1'},{id:2,event_name:'event 2'}];

In this setup, the id corresponds to the identifier in the first array, and the event_name is used to filter the events property within the first array;

A potential solution involves utilizing a for-in loop as outlined below:

const data = [
  {
    id: 1,
    date: '2023-10-01',
    events: [{ id: '1a', name: 'event 1' }, { id: '1b', name: 'event 2' }],
  },
  {
    id: 2,
    date: '2023-10-02',
    events: [{ id: '2a', name: 'event 1' }, { id: '2b', name: 'event 2' }],
  },
  {
    id: 3,
    date: '2023-10-03',
    events: [{ id: '3a', name: 'event 1' },{ id: '3b', name: 'event 2' }],
  },
];

const ev_data = [{id:1,event_name:'event 1'},{id:2,event_name:'event 2'}];

//this modifies the original array, data
for(const i in data) {
    const cur = data[i];
    const ev = ev_data.find(({id}) => id === cur.id);
    if( ev ) {
        cur.events = cur.events.filter(({name}) => name === ev.event_name);
    }
}

console.log( data );

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

NodeJS npm module installed globally is unable to run the main/bin JavaScript file using node command

Here is an example of my package.json: { "name": "example-module", "version": "1.0.0", "bin": "./bin/example-module.js", "main": "./bin/example-module.js", "description": "Example module description", "homepage": "http://my.home.page.com", " ...

Posting a JavaScript string to a C# backend in ASP.NET Core MVC: A step-by-step guide

I am a beginner in ASP and facing an issue while attempting to pass a string from my JavaScript code to my controller. The intention is to utilize this string for querying my database. JavaScript function findEmployees(userCounty) { $.ajax({ t ...

Place the tiniest positive whole number into an array containing only distinct integers

I'm currently tackling this interview question: given an array of unique positive integers, how can we find the smallest number that needs to be inserted to ensure all integers remain unique? The algorithm must have a time complexity of O(n) and a spa ...

Tips for submitting a form with multiple fields that share the same name attribute using ajax:

I have created an HTML form <html> <head></head> <form> <input type="text" name="question[]" /> <input type="text" name="question[]" /> <input type="file" name="image" /> <input type="submit ...

Error: Unable to access the 'classList' property of null in HTMLSpanElement.expand function

Encountering a minor issue with my javascript code. Following a tutorial for a seemingly simple task: link What I did: Adapted the HTML from the tutorial to fit my desired visual outcome while maintaining correct class and id attributes. Utilized identic ...

A guide on integrating array map with a v-for loop in Vue

Struggling to understand how to implement a loop within another loop in Vue? This task might seem simple with React, but Vue presents its own challenges when it comes to using loops with arrays in templates/JSX. The input data follows a specific format fr ...

Invoking Swift from a UIWebView using Javascript

Hey there! I am currently exploring the process of making a call from a JavaScript function in a UIWebView to Swift in iOS 10. To do this, I have set up a basic project for testing purposes, and you can find the code below. import UIKit class ViewControl ...

Creating a Multi-stop Gradient Effect on Lines in THREE.js

Learn how to create a stunning two-color gradient effect on a THREE.js line with this helpful guide: Color Gradient for Three.js line Have you ever wondered how to achieve a multi-stop color gradient along a line in THREE.js? Find out the solution here - ...

Why Does React Material-UI Switch Styling Keep Changing Sporadically?

Currently, I am trying to integrate a switch component from MUI into my code. Strangely enough, upon the initial page load, the switch appears exactly as it should - identical to the one displayed on the MUI site. However, upon reloading the page, it under ...

Showing a dynamically updated array in Angular

Within my Angular Application I am utilizing an ngFor loop in the component to display an array. Now, I am filtering the data from the array and aiming to update the newly filtered array in place of the original one. While I can successfully display the ...

JavaScript does not recognize external styles (when an if statement is involved)

I recently started learning web development, and I encountered an issue while working on a responsive design project. When the hamburger menu is clicked, the lines for expansion that are defined in an external CSS file are not being detected. Instead, new ...

Struggling to resolve the issue while deploying a Next.js application on Netlify. The error seems to be stemming from the import of an image and its

I attempted to eliminate the code on line 4 and line 15 in index.js, then deployed it on Netlify. The functionality is working correctly, but the image is not displaying as desired. However, when I try to modify the code with just lines 4 and 15 included, ...

Leverage the power of Webpack to make Vue available globally

Currently, I am dealing with a situation in a legacy Rails application that has undergone some migration to integrate Webpacker and Vue. Additionally, we are utilizing a legacy script loaded through a CDN that also requires Vue. However, instead of bundlin ...

Using jQuery to vertically center a div

When a vertical menu on my website is clicked, it pops out from the left side of the screen. The content inside is vertically centered using CSS transformations. While expanding to show sub-items, everything remains centered. However, there's an issue ...

What is the method to retrieve results using 'return' from NeDB in vue.js?

Seeking assistance on retrieving data from NeDB within a method in a .vue file using electron-vue. Currently, I am aware that the data can be stored in a variable, but my preference is to fetch it using 'return' as I intend to utilize the result ...

Tips for concealing the background HDR map display in three.js without compromising the HDRI's contribution to the lighting effects

In my code, I have implemented the following example: Source: https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_gltf.html#L53 While HDRI lighting works perfectly, I am struggling to hide the HDR map from the background. Is there a way ...

javascript has a funny way of saying "this is not equal to this" (well,

Sample 1 var Animal = function () { var animal = this; this.makeSound = function() { alert(animal.sound); } } var dog = new Animal(); dog.sound = 'woof'; dog.makeSound(); Sample 2 var Animal = function () { this.makeSound = ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

removing identical elements from an array

I need assistance filtering out duplicate values from an array. Here is an example of my current array: array(0=>"1", 1=>"1", 2=>"3", 3=>"1", 4=>"6"); I am looking to achieve the following result: array(0=>"1", 1=>"3", 2=>"6"); ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...