Seek & Destroy: filter callback function doesn't take variable

Seek & Destroy: filter callback function doesn't take variable
0.0 0

#1

Hi,

I already found a different route to solve the Seek & Destroy challenge, but still wondering why my first attempt didn’t work.

I first created conStr as the filter string, which works fine. But when I use that variable in the actual filter callback function (hasToGo) than it is disregarded somehow. Whereas when I manually type the exact same contents of conStr, it works just fine.

Wonder where this goes wrong for future challenges.

Thanks,
Erlend

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  var conStr = "";
   for (var i = 1; i < args.length; i++) {
  	if (i == 1) {
  	 	conStr = "value != " + args[i];
    	} else {
   		conStr += " && value != " + args[i];
    	}
   }
 console.log(conStr);
 function hasToGo(value) {
//   return value != 2 && value != 3;
     return conStr ;
 }

var filtered = args[0].filter(hasToGo);
console.log(filtered);
 }

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

#2

The basic problem is your solution idea is too meta for the code you wrote - the fix is below

function hasToGo(value) {
   return eval(conStr)
}

The key point to understand here is conStr is a string - it is not code - it is a representation of code - you need something else to recognize it as code and run it - that something is eval

The eval function is best avoided till you have a thorough understanding of all javascript - no question it can make life look very easy


#4

Thanks a lot, makes a lot of sense.