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

Tips for repairing a button using a JavaScript function in an HTML document

I am currently working on extracting titles from body text. To achieve this, I have created a button and linked my function to it. The issue I am facing is that when I click on the button, it disappears from its original position. I intend to keep it in pl ...

Mist Conceals Celestial View (THREE.JS R76)

I have a cylindrical camera setup with fog to hide the end of the tube. However, I am trying to make the skybox visible through the alpha map sides of the cylinder. The current issue is that the fog is blocking the visibility and I'm looking for a sol ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

What does Angular classify as a watcher?

What qualifies as "watchers" within Angular? Are watchers the only type of monitoring mechanism, or do other Angular elements like ngModel also serve as watchers? Am I overlooking something crucial? For example, do watchers play a role in enabling directi ...

Adding icons to form fields based on the accuracy of the inputs provided

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Assignment 2 - Website Bui ...

jQuery is optimized to work specifically with select id tags

Here is the HTML code snippet I've put together, along with my script. While I admit it might look a bit messy, please bear with me as I'm still in the learning phase. If anyone could offer some assistance on this matter, I would be extremely gra ...

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

When _.template is evaluated in Node JS, it freezes and encounters a ReferenceError causing the program to halt

I've noticed a strange issue when using http://underscorejs.org/ with Node JS: If a reference error occurs while evaluating a template function, Node JS will become unresponsive! Examples: EXAMPLE 1: SUCCESSFUL SCENARIO: var template = "<%= tes ...

A collection of items that mysteriously affix themselves to the top of the page as

Unique Context In my webpage, I have a specific div element with the CSS property of overflow: auto. Within this scrolling div, there is structured content like this: <h3>Group A</h3> <ul> <li>Item 1</li> <li>I ...

"Troubleshooting the ineffectiveness of JavaScript's

(After reviewing all questions and answers related to this issue, I have not found a solution that works for me.) Here is the code snippet in question: var timeoutHandle; function showLoader(show) { if (show) { $('.loader').html(&a ...

What is preventing me from mapping an array to Material UI Chip components?

I'm currently working with Next.js and I'm trying to map an array of elements to Material-UI chip components. However, when I compile the code, I encounter the following error: Error: Element type is invalid: expected a string (for built-in comp ...

XHR object encountered a 404 error while attempting a GET request with an unknown URI component name

Currently, I am attempting to design a text box that triggers a server query as soon as a character is entered into it. However, I am encountering an error message that is puzzling me: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Do ...

Issue with React Toggle functionality on mobile devices

I have a hamburger toggle that I found in a template, but it doesn't seem to be functioning correctly. How can I activate the on/off toggle feature? When I click the toggle, nothing happens. What am I missing? <div data-testid="header"> ...

The controller is unable to retrieve the posted value

Whenever I try to retrieve the post value from my controller, it always returns null. Even though I can see that there is a post value present when I check, for some reason, I am not able to access that value in my controller. Does anyone know what the p ...

Issues Persist with Vue CLI 3 and Axios - Proxy Server Failure

My VueCLI frontend application is running on http://localhost:8080 in development mode. I encountered a CORS issue when trying to access API services from http://localhost:36856. Despite setting up proxy server configuration in vue.config.js, the problem p ...

Incorrect rendering of the <li> tag

I've been working on creating a simple web "to do list" but I've encountered an issue. When I manually add todos and click on them, the 'text-decoration: line-through;' property is ignored, and I can't see the strikethrough effect ...

Client Blocking Issue: ExpressJS encountering problem loading JavaScript file

I recently deployed my express app on a server (specifically, I used Heroku). Everything functions perfectly when I test the app locally. However, when I access the app online, I encounter an issue with a net::ERR_BLOCKED_BY_CLIENT error. This error states ...

What is the best way in Javascript to retrieve and process multiple stream chunks from a single API request using the fetch() method

I'm dealing with a Node/Express backend where there is a lengthy (10 - 15sec) API call that is responsible for setting up a user's account. To initiate this action from the front-end, I simply use a fetch('my/api/url') GET request. My ...