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

Filter similar names in object array JavaScript

so here is a problem I’ve been struggling with for a little bit now. I want to filter a list of objects but the code seems to work only for arrays. I can i reach the same result with objects? Basically what I want is something like: if card.name = jose. then remove jose._R
if card.name = jose._R then remove jose.

Code:

var data = {'cards' : 
    [
    {'name': "jose."}, 
    {'name': "jose._R"}, 
    {'name': "rodrigo."}, 
    {'name': "rodrigo._R"}, 
    {'name': "jojo."}, 
    {'name': "jojo._R"},
    ]
    };
    
let dataName = data.cards[0].name;
let rev = data.cards[0].name + "_R";

var data2 = ["jose.", "jose._R", "rodrigo.", "rodrigo._R", "jojo.", "jojo._R",];
let dataName2 = data2[0];
let rev2 = data2[0] + "_R";


if(dataName2.endsWith('.')){
    data2 = data2.filter(function(f) {return f !== rev2});
};

if(dataName.endsWith('.')){
    data = data.cards.filter(function(f) {return f !== rev}); // NOT WORKING! It doesn't remove the object array... :-(
};

console.log(data);
console.log(data2);

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

>Solution :

In your filter function

function(f) { 
  return f !== rev; 
}

You are comparing the entire object { 'name': 'rodrigo.' } to the string so they will never be equal. Instead you should compare the name property with the given string:

function(f) {
  return f.name !== rev;
}
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