skip to Main Content

I want to remove all Id from dep_array that exists in the dep_log array and have deleted=0.

//array of departments ID
dep_array=['3', '2', '1'];


dep_log=[{"department_id": "3", "creation_date": "2023-05-13 17:59:27", "created_by": "1", "deleted":"0"} ,
{"department_id": "2", "creation_date": "2023-05-13 17:59:11", "created_by": "1", "deleted":"1"} ,
{"department_id": "1", "creation_date": "2023-05-13 09:46:25", "created_by": "1","deleted":"0"} ]

the reults should be stord in new array the filtered IDs

3

Answers


  1. You can do it via Array.filter() and Array.some()

    let dep_array=['3', '2', '1','4','5']
    
    
    let dep_log=[
    {"department_id": "3", "creation_date": "2023-05-13 17:59:27", "created_by": "1", "deleted":"0"} ,
    {"department_id": "2", "creation_date": "2023-05-13 17:59:11", "created_by": "1", "deleted":"1"} ,
    {"department_id": "1", "creation_date": "2023-05-13 09:46:25", "created_by": "1","deleted":"0"}
    ]
    
    dep_array = dep_array.filter(d1 => !dep_log.some(d2 => d2.department_id == d1 && d2.deleted == 0))
    console.log(dep_array)
    Login or Signup to reply.
  2. You can use JavaScript’s array method filter to get a sub-array conditionally.

    Documentation for filter

    //array of departments ID
    const dep_array=['3', '2', '1'];
    
    
    const dep_log=[{"department_id": "3", "creation_date": "2023-05-13 17:59:27", "created_by": "1", "deleted":"0"} ,
    {"department_id": "2", "creation_date": "2023-05-13 17:59:11", "created_by": "1", "deleted":"1"} ,
    {"department_id": "1", "creation_date": "2023-05-13 09:46:25", "created_by": "1","deleted":"0"} ];
    
    const filteredArr = dep_log.filter(item => dep_array.includes(item.department_id) && Number(item.deleted))
    
    console.log(filteredArr)
    Login or Signup to reply.
  3. You may combine the filter function with find function to get your desired array.

    //array of departments ID
    const dep_array = ['4', '3', '2', '1'];
    
    const dep_log = [
      {"department_id": "3", "creation_date": "2023-05-13 17:59:27", "created_by": "1", "deleted":"0"},
      {"department_id": "2", "creation_date": "2023-05-13 17:59:11", "created_by": "1", "deleted":"1"},
      {"department_id": "1", "creation_date": "2023-05-13 09:46:25", "created_by": "1", "deleted":"0"}
    ];
    
    const filtered_array = dep_array.filter(id => 
      dep_log.find(log => log.department_id === id)?.deleted != '0'
    );
    
    
    // "4" does not appear in the dep_log, keep
    // "2" appears in the dep_log but with deleted=1, keep
    console.log(filtered_array);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search