KathyBlue KathyBlue - 14 days ago 6
Javascript Question

JavaScript Replace matching members of array compared to other array

I got this task and I can't get how to replace the matches with the string "BUSTED", can you help me please. I'm new to JS. Most probably there is a way more elegant way to do this. Any help appreciated.

You're given two arrays: one that holds every member of fCommunity and another one
that holds every possible suspect.
Replace every fCommunity member from the Suspect list with the word "BUSTED"


var fCommunityMembers = ['A','B','C'];
var SuspectList = ['F','X','B','Z','Y','C','ZS','D','K','M','N'];


I managed to retrieve the matching members but how do I replace them in the suspect list?:

Array.prototype.diff = function(SuspectList) {
var ret = [];
this.sort();
SuspectList.sort();
for(var i = 0; i < this.length; i += 1) {
if(SuspectList.indexOf( this[i] ) > -1){
ret.push( this[i] );
}
}
return ret;
};

var ListOfMatches = Array.from(fCommunityMembers.diff(SuspectList));

console.log( ListOfMatches );

Answer

Use Array.prototype.map() to iterate fCommunityMembers. If an member is found in the SuspectList return BUSTED, if not return the member:

var fCommunityMembers = ['A','B','C'];
var SuspectList = ['F','X','B','Z','Y','C','ZS','D','K','M','N'];

var result = fCommunityMembers.map(function(member) {
  return SuspectList.indexOf(member) !== -1 ? 'BUSTED' : member;
});

console.log(result);