Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove arrays from an Array if a certain values exists within a list

Pretty new at JavaScript, just trying to remove an entire array within my data if certain values are listed in the del_values array.

What would be the best approach to this problem?

data = 
[['true', 'visiting-today', 'DVM-Wiessman','J-001'],
['false', 'visiting-tommorrow', 'DVM-Stevens','K-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['false', 'visiting-tommorrow', 'DVM-Kon','J-001']]


var del_values = ['J-001','K-001'];

function remove_from_list(list,deleted_values) {
    for( var i = 0; i < deleted_values.length; i++) { 
        result = list.filter(dat => !dat.includes(deleted_values[i]));
    }
    return result;
}

Actual Result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data = 
[ [ 'true', 'visiting-today', 'DVM-Wiessman', 'J-001' ],
  [ 'true', 'visiting-tommorrow', 'DVM-Stevens', 'Z-001' ],
  [ 'false', 'visiting-tommorrow', 'DVM-Kon', 'J-001' ] ]

Desired Result — to remove an entire array within the data if it contains any of the values listed in del_values

data = 
[[ 'true', 'visiting-tommorrow', 'DVM-Stevens', 'Z-001' ] ]

>Solution :

You can use Array.prototype.every inside filter’s callback:

const data = [
  ['true', 'visiting-today', 'DVM-Wiessman', 'J-001'],
  ['false', 'visiting-tommorrow', 'DVM-Stevens', 'K-001'],
  ['true', 'visiting-tommorrow', 'DVM-Stevens', 'Z-001'],
  ['false', 'visiting-tommorrow', 'DVM-Kon', 'J-001']
]

const del_values = ['J-001', 'K-001'];

function remove_from_list(list, deleted_values) {
  return list.filter(arr => arr.every(el => !deleted_values.includes(el)))
}

console.log(remove_from_list(data, del_values))

function remove_from_list(list,deleted_values) {
    for( var i = 0; i < deleted_values.length; i++) { 
        result = list.filter(dat => !dat.includes(deleted_value[i]));
    }
    return result;
}

The main issue in your code is at each iteration list is being filtered so the previously filtered array gets reassigned.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading