removing an item from a nested array through the use of the filter() method

I have been struggling to remove an element with a specific ID from a nested array.

Are there any suggestions on how to effectively utilize the filter() method with nested arrays?

The goal is to only eliminate the object with {id: 111,name: "A"}.

Below is the snippet of code I've been working on:


var array = [{
    id: 1,
    list: [{
        id: 123,
        name: "Dartanan"
    }, {
        id: 456,
        name: "Athos"
    }, {
        id: 789,
        name: "Porthos"
    }]
}, {
    id: 2,
    list: [{
        id: 111,
        name: "A"
    }, {
        id: 222,
        name: "B"
    }]
}]

var temp = array
for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array[i].list.length; j++) {
        temp = temp.filter(function(item) {
            return item.list[j].id !== 123
        })
    }
}
array = temp

Answer №1

If you want to apply the function forEach and run the function filter on each array item list.

var array = [{    id: 1,    list: [{      id: 123,      name: "Dartanan"    }, {      id: 456,      name: "Athos"    }, {      id: 789,      name: "Porthos"    }]  },  {    id: 2,    list: [{      id: 111,      name: "A"    }, {      id: 222,      name: "B"    }]  }];

array.forEach(o => (o.list = o.list.filter(l => l.id != 111)));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

To keep the data immutable, utilize the function map:

var array = [{    id: 1,    list: [{      id: 123,      name: "Dartanan"    }, {      id: 456,      name: "Athos"    }, {      id: 789,      name: "Porthos"    }]  },  {    id: 2,    list: [{      id: 111,      name: "A"    }, {      id: 222,      name: "B"    }]  }],
    result = array.map(o => ({...o, list: o.list.filter(l => l.id != 111)}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To easily filter elements based on a specific property, consider creating a new array with only the desired elements.

const filteredArray = originalArray.map(item => (
  {
    ...item,
    list: item.list.filter(element => element.id !== 111)
  }
));

If your runtime environment does not support the spread operator, you can use Object.assign as an alternative method.

Answer №3

Array.filter is used to work with elements:

var myArray = [{something: 1, list: [1,2,3]}, {something: 2, list: [3,4,5]}]

var filtered = myArray.filter(function(element) {
     return element.something === 1;
     // true = keep element, false = discard it
})

console.log(filtered); // displays [{something: 1, list: [1,2,3]}]

You can implement it in this way:

var array = [{
    id: 1,
    list: [{
        id: 123,
        name: "Dartanan"
    }, {
        id: 456,
        name: "Athos"
    }, {
        id: 789,
        name: "Porthos"
    }]
}, {
    id: 2,
    list: [{
        id: 111,
        name: "A"
    }, {
        id: 222,
        name: "B"
    }]
}]

for (var i = 0; i < array.length; ++i) {
  var element = array[i]
  
  // Filtering the list
  element.list = element.list.filter(function(listItem) {
      return listItem.id !== 111 && listItem.name !== 'A';
  })
}

console.log(array)

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

Using AJAX to add an event listener and passing parameters to a separate function

Short and sweet - I've got a loop that creates a series of dynamic buttons, and when one of them is clicked, I need to pass its id attribute to another file to generate a new page on the fly. Here's the code snippet: for (var i in data.contacts ...

AngularJS allows for the creation of cascading dropdown selects, where the options in the second select

I'm struggling to access the version data stored in the server model, but it's not cooperating. My suspicion is that when the page loads, the initial data from the first select isn't available yet because it hasn't technically been sel ...

Clicking to remove added child element

I have written a script that creates an image popup when the site loads. Here is the code: <script type="text/javascript"> function showPopup() { var div = document.createElement('div'); div.className += 'popup'; div.inne ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

Issue with ngStyle function in Internet Explorer

Within my Angular 4 application, I have defined styles as shown below: [ngStyle]="{'border': getInterleaveColor(i)}" The following function is also included: getInterleaveColor(auditNumber) { var borderProperties = '2px solid'; ...

"Trouble with the accordion: How to make the first one open

Is there a way to make the first tab automatically expand when the page is refreshed? I want the General tab to be expanded by default like this: General (top header) (-) lorem ipsum (-) lorem ipsum doller amu site amu doller lorem ipsum (+) lorem i ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

A guide on conditionally rendering components in React

When I try to add a nested if statement in JSX, condition ? true example : false example works perfectly. However, when I change it to if(condition) { ... }, it displays an error in the console: https://i.stack.imgur.com/TIBRo.jpg Example with one-line c ...

Using Angular to share JSON data efficiently between controllers

Greetings everyone, I am a beginner in Angular and not very skilled with JavaScript. The issue I'm facing is that although this setup successfully fetches the JSON data, whenever I modify certain object properties, they revert back to their original s ...

The style was not applied from because it has a MIME type of 'text/html', which is not a supported stylesheet MIME type, and strict MIME checking is turned on

I'm currently working on creating a Google web app that relies on a Google sheet in the backend. I prefer to develop locally in VSCode since the editor in Google Apps Scripts is quite limited. Additionally, I aim to incorporate Vue3 into my project. ...

The collapsible list feature that includes the use of plus and minus signs is malfunctioning

Below is the script that I wrote to address this issue, but for some reason the + and - swapping is not functioning correctly. $('.showCheckbox').click(function(e) { var dynamicBox = $(this).attr('val'); var collapseSign = $(th ...

Determine the type of element existing in the table cell

Currently, I am utilizing protractor to iterate through table cells in an attempt to verify the presence of a checked checkbox. var elements = element.all(by.css(columncssname)); elements.each(function (cell, index) { <--need to confirm if check ...

I'm struggling to find the perfect configuration for Vite, JSconfig, and Aliases in Visual Studio Code to optimize Intellisense and Autocomplete features

After exclusively using PHPStorm/Webstorm for years, I recently made the switch back to Visual Studio Code. The main reason behind this decision was the lightweight nature of VSCode and its widespread availability as a free tool, unlike paid services. I s ...

Navigating with Vue Router in a Nuxt JS vuex Store

In my app, I'm currently developing a login/register system using Firebase and Vuex for authentication and database management. Within Nuxt JS, I have implemented actions to create a user, log them in, and sign them out. After a successful registrati ...

Why does the Next.js GET index request keep fetching multiple times instead of just once?

Currently, I am encountering an issue while working on a tutorial app with Next.js. One of my components is not rendering due to what seems like multiple executions of a simple GET request for an index page. The problem perplexes me, and I need some assist ...

Is there a way for me to gain entry to this array in vuejs?

Can anyone help me with accessing the objects in this array? I am using laravel, inertiajs, and vuejs. I am passing a variable from a laravel controller to a vuejs component with inertia.js. https://i.stack.imgur.com/p7yjL.png https://i.stack.imgur.com/y ...

A guide on how to retrieve POST form fields in Express

My form design is quite simple: <form id="loginformA" action="userlogin" method="post"> <div> <label for="email">Email: </label> <input type="text" id="email" name="email"></input> </div> & ...

Looking for assistance in implementing specific styling techniques with React

Trying to implement a slider on my React page sourced from a Github repository. The challenge lies in adding the CSS as it is in JS format. Even after incorporating webpack and an npm compiler, the styling seems unrecognized. Any suggestions or solutions ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

Presenting a dynamic selection of files from a database in a dropdown menu with looping functionality using Laravel

I have a dropdown menu that I want to use to display input files from the database based on the selection made. Here is the scenario: When a dropdown option is chosen, it should show input files derived from the "loop_atachment" table (based on the select ...