skip to Main Content

How to remove selected item and nested item too from array using javascript

const data =  [
    {id: 1, name: 'Gill'},
  {id: 2, name: 'Gill2'},
  {id: 3, name: 'Gill3'},
  {id: 4, name: 'Gill4'},
  {id: 5, name: 'Gill5'}
]

if i pass strong text console.log(filterID("4", data))

then output should be

[
    {id: 1, name: 'Gill'},
  {id: 2, name: 'Gill2'},
  {id: 3, name: 'Gill3'}
]

id 4 and 5 will be removed and so on if anything came after 4

my tried code is

https://jsfiddle.net/p5fxhcbk/2/

Thanks

2

Answers


  1. function filterID(id, data) {
      return data.reduce((arr, item) => {
        if (item.id != id) {
          if (item.children) item.children = filterID(id, item.children)
          let newArr = arr.filter(filterID(id,item.children));
        }
        return newArr   
      }, [])
    }
    
    Login or Signup to reply.
  2. First we just need to find the index of an element.
    Next simply get the array fragment sliced to the found index.
    If the index is not found, the origin array is returned.
    Check documentation for findIndex and slice

    const data =  [
      {id: 1, name: 'Gill'},
      {id: 2, name: 'Gill2'},
      {id: 3, name: 'Gill3'},
      {id: 4, name: 'Gill4'},
      {id: 5, name: 'Gill5'}
    ]
    
    function filterOut(arr, removeFromNode) {
      const idx = arr.findIndex(item => item.id == removeFromNode)
      return idx < 0 ? arr : arr.slice(0, idx)
    }
    
    console.log(filterOut(data, "4"))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search