# Wherefore art thou

Oh man! I just finished this exercise, but not in the most elegant fashion! I needed 4 variables, 3 if statements and a for loop to get the job done. It’s making me wonder: would it be smart of me to review other answers and try to learn how I could have coded this more efficiently, or should I just keep pushing forward and try to complete these exercises through “any means necessary.” I’m just a bit worried I might develop some bad habits of I keep going forward. Is that nonsense?

PS for some comic relief here is the code I wrote for the exercise:

``````function whatIsInAName(collection, source) {

var arr = [];
var myKey = Object.keys(source);
var key1 = myKey[0];
var key2 = myKey[1];

for (var i=0; i<collection.length; i++) {

if (myKey.length > 1) {
if (collection[i][key1] === source[key1] && collection[i][key2] === source[key2]) {
arr.push(collection[i]);
}
}
else if (collection[i][myKey] === source[myKey]) {
arr.push(collection[i]);
}
}
return arr;
}

whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });
``````

The thing about picking up bad habits is that eventually, you’ll come to realize why they are bad habits. Not only that, but you’ll understand why far better than if someone tried to explain it to you.

Having said that, its always good to check out how other people solved problems, especially if you have already solved that problem yourself. I wouldn’t get too hung up on writing perfect code now. The more code you write and the more mistakes you make, the more you’ll learn.

I don’t like how I finished most of those algorithms, that’s why I finished them, moved on and will come back to write them more efficiently when I know more.

Also, there is nothing comic about your code. It works and it does what you intended it to do, nothing wrong with that. Just keep plugging!

2 Likes

Don’t. I did that. Waste of time. You don’t know what you don’t know.

You should start reading other’s code as soon as possible. It’s invaluable to see how others solved the same problem. That’s why I recommend https://www.codewars.com/. After solving a problem you can see other solutions marked as ‘best practices’ or ‘clever’, read comments, ask questions etc.

If you do it before you even attempt to solve the problem yourself it is called cheating. If you solved it or at least spent a reasonable amount of time trying to solve it and then you look at the answer, it is called learning.

3 Likes