Some question JS

so I have this code, and I would like to check if source is part of item.last shouldn’t it return true?

  **Your code so far**

function whatIsInAName(collection, source) {
const arr = [];
// Only change code below this line
const newArr = [source]
console.log(collection.some((item) => {
item.last === source;
}))

// Only change code above this line
return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36

Challenge: Wherefore art thou

Link to the challenge:

You have a couple of issues with your solution.

First, your function whatIsInAName doesn’t return anything. You log out what you believe to be the answer, but you don’t return it from the function.

Next, your callback doesn’t return anything.

Next, you are hard coding to test the property “last”.

And lastly, you are checking it against source, which is an object.

I think your approach is off. Forget about code for a second. Imagine you were coming up with a procedure for someone that can follow instructions perfectly, but can’t use any intuition. What methodical procedure would you give them. Right now the pseudo code for what you have would be.

set arr to an empty array
set newArr to an array containing source
log to the screen if any are true:
   loop items in collection
    check if each item has a property "last" that matches the object source
return arr

What would be the pseudo code for a working procedure.

Hint: You will probably need two loops, even if one is hidden in a prototype method.

thanks for your comment.
I want to say this is usually my process I console log a lot of stuff to output what’s going on in my brain, it doesn’t necessarily mean it is the final answer.

what does hard code mean in this context? & generally

what is the problem with that?
ty.

edit: i wanted to check if that some function passes it but I don’t understand why it fails. if it passes then maybe I can filter if (true)

what does hard code mean in this context? & generally

It means that it is written explicitly in the code, instead of using a variable:

item.last === source;

Here, you are checking explicitly for the property “last”. You have hard-coded it, instead of using a variable. It will only check for that property name. Some of the examples don’t care about the last name.

what is the problem with that?

I expect the left hand of the above test (in the case of “last”) to be a string. source is an object. They will never be equal, ever.

edit: i wanted to check if that some function passes it but I don’t understand why it fails. if it passes then maybe I can filter if (true)

You are using some correctly (except that your callback doesn’t return anything.) The issue is if that is what you should be checking.

Again, think out the algorithm. Once you understand the algorithm, then you can code it. They are two different things. Forget about JS for a moment and just think through the step by step process, the algorithm.

sometimes it is hard to think everything at once so I try to type a step by step I find it easier sometimes. my idea mainly was to see if source is a part of collection and then filter what I need. so I tried with include etc but then its an object and so on.

100%. That is the trick of computer programming - translating human thinking into computer thinking.

If my gets home with a car load of groceries and tells me to unload it, the human way of thinking about it is:

unload groceries from car

We instinctively know how to handle that. We don’t need a detailed process. A computer program would be something like:

loop going to car until groceries empty
  if frozen groceries
    grab an armful of frozen groceries 
    walk to kitchen
    put away groceries
    continue next loop
 else
    grab an armful of groceries 
    walk to kitchen
    put away groceries
    continue next loop
lock car
return to apartment
close front door
kiss wife on cheek

That is how a computer things. It can’t intuit its way through the problem. It can’t assume anything. It’s like having a very simple person that can follow instructions perfect, but you have to explain everything perfectly, step by step.

We could even go further - how does it mean to “put away groceries”? What goes in what cabinet? This assumes that there is a pre-understood algorithm.

This is the level that you have to think for algorithms.

my idea mainly was to see if source is a part of collection and then filter what I need.

I understand what you are saying, but I think you are thinking of the algorithm wrong. Please write out what you are thinking in pseudo code. If you can do it in pseudo code, then you can code it. If you can’t do it in pseudo code, then you don’t really understand the algorithm. This is a way to break the task into smaller, more manageable pieces.

1 Like

Okay I’ll try.
I want also to add that that I feel looping it with for might be easier for me in this specific challenge, but since I’m studying I prefer to get stuff done in a neater way.

Sometimes my brain already has an idea what to do even before I gathered my thoughts to it, but I don’t think it’s necessarily bad. to me it feels like instincts I feel like it’s good to use it.

100%. Do what you have to do. If you’re more comfortable with a for loop then use that. Sometimes I actually write it initially as a for loop and then refactor it later.

Get a working solution, that is the number 1 goal. You can worry about pretty later.

Sometimes my brain already has an idea what to do even before I gathered my thoughts to it, but I don’t think it’s necessarily bad.

No. But you have to remember that computers don’t have instincts. And they don’t have intuition. And they don’t know what you were really thinking.

to me it feels like instincts I feel like it’s good to use it.

Sure. Instinct can be a great tool in programming. But instincts can be built from experience. You don’t have “computer algorithm instincts” yet. You will build them. Every algorithm you finish builds up what I call the “algorithm brain”. There are definitely times, especially when doing algorithms competitively, where you need to use your instincts to find a solution, or at least a path to one possible solution. But that gets built with time. For now, just take it slow and think through it.

Let’s see what you come up with for a pseudo code algorithm for this. This is literally something I write out sometimes when confronted with a tough problem. With instinct, you can “wing it” a bit more, but if you need it, write it out. It is a great learning and thought organizing tool.

loop through collection
if (element has source)
return element
*/

this is for example something that came on with a brief thinking, what do you think?

OK, that’s a start. I think that checking if element has the source (remembering that the source might have more than one key/value pair) needs to be fleshed out. And again, don’t worry about getting the JS right. Just get the ideas down.

And I was trying to hint before, you might need another loop, inside the first one.

Thank you for the tips.

Another question.

What does flesh out mean?

I need to highlight that source key with the collection key did you mean this?

I’m not sure if you already figured out what to do but let me offer a help here.
First, instead of creating new array using [source], use Object.keys(source). Because your way will create an array containing objects of source.
Then I would create a function that will check the above conditions while iterating first arg which is an array. Then use for or forEach to push obj into arr
// returns true or false
const hasSourceKey = obj => Object.keys(source).every(elem => obj.hasOwnProperty(elem) && obj[elem] === source[elem]);
collection.forEach(element => {
if(hasSourceKey(element)) {arr.push(element)}
});
return arr;
I think this will help.

I see a lot of hints here, I already have an idea in my mind. I first try to solve with my own idea, unless I am really stuck. So I wont be reading far a head sorry.

I mean to fill it out. You have this:

loop through collection
  if (element has source)
    return element

The first line of your pseudo code matches mine. I think your second line is just a skeleton of an idea, you need to “flesh it out”, add some meat to it. You need to explain how to check “if element has source”. I don’t think it is as simple as that question implies. Again, remember that source may have more than one thing in it. Refer back to my previous hints.

function whatIsInAName(collection, source) {
  const arr = [];
  // Only change code below this line
  const sourceArr = Object.values(source) // source key values  in an array
  for (let i = 0; i < collection.length; i++) {
    const newArr = Object.values(collection[i]);
    const joinedArr = newArr.concat(sourceArr)
    const condition = joinedArr.some((elem, index) => joinedArr.indexOf(elem) !== index)
    if (condition) {
      arr.push(collection[i])
    }
  }
  /*loop through collection to get keys/values
   check if source key/value equals to collection/key values

  */

  // Only change code above this line
  return arr;
}

whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 });

That’s what I was able to come up with.
my problem is in this code that the some function takes (elem) only 1 number but I need elem to be the whole sourceArr is there any way to do that?

Also I tried doing your way and writing a full pseudo code, but I’m getting stuck. It’s probably not the best practice but just doing it all in my head gives me some kind of a flow.

I’m not at a computer at the moment so I can’t test this, but it’s still not loking right to me,

You say you can’t do the pseudo code - what did you come up with? Can you write out the pseudo code for what you are trying here? Or at least explain it?

Again, when in doubt, log stuff out:

function whatIsInAName(collection, source) {
  const arr = [];
  // Only change code below this line
  const sourceArr = Object.values(source) // source key values  in an array
  console.log('sourceArr', sourceArr)
  for (let i = 0; i < collection.length; i++) {
    console.log('\n*', i, 'collection[' + i + '] =', collection[i])
    const newArr = Object.values(collection[i]);
    console.log('*', i, 'newArr =', newArr)
    const joinedArr = newArr.concat(sourceArr)
    console.log('*', i, 'joinedArr =', joinedArr)
    const condition = joinedArr.some((elem, index) => {
      console.log('*** elem =', elem, ' and index =', index)
      console.log('*** joinedArr.indexOf(elem) =', joinedArr.indexOf(elem))
      console.log('*** joinedArr.indexOf(elem) !== index', joinedArr.indexOf(elem) !== index)
      return joinedArr.indexOf(elem) !== index
    })
    console.log('*', i, 'condition =', condition)
    if (condition) {
      console.log('*', i, 'pushing', collection[i])
      arr.push(collection[i])
    } else {
      console.log('*', i, 'not pushing')
    }
    console.log('*', i, 'arr after', arr)
  }
  /*loop through collection to get keys/values
   check if source key/value equals to collection/key values

  */
  console.log('\nreturning', arr)
  console.log('')
  // Only change code above this line
  return arr;
}
console.clear()

console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }));

If I were to write pseudo code for your approach, I would say this:

make array of source values
loop collection objects
  get array of collection object values
  join (concat) source values array and collection object values array
  if some first index of some values in joined array are not the first
    push collection object onto answer array
return answer array

Again, I think this is the wrong approach. First of all, findIndex returns the index of the first occurrence. So, if will be a different index for any repeated values (it will be the index of the first occurrence but you are checking it against the location of the second occurrence - that will always fail if there are repeated values.

Let’s look at the second object in the above test code. It is asking does this collection object ({ "bat": 2 }) have key/value pairs that match every key/value pair in the source ({ "apple": 1, "bat": 2 }). The answer is no, it doesn’t have the "apple": 1 k/v pair. Your code says:

OK, get the values from the object ([2]) and concat them with the values of the source ([1, 2]), giving us a joined array of ([2, 1, 2]). Loop through those and see if the first index of each element matches the index of the current one.

So, we loop inside our some method.

loop 0
  index is 0, and findIndex(2) returns 0, so our inequality is false
  index is 1, and findIndex(1) returns 1, so our inequality is false
  index is 2, and findIndex(2) returns 0, so our inequality is true

That last one is the problem. It is not testing what you think it is testing. Our some will always be true if that value occurs more than once in our joined array.

The other big problem is that you are only checking values. The instructions say: “matching name[key] and value pairs”. But you are only checking values. You need to not see if just values match, but it k/v pairs match. In the above example, you don’t need to just check if anything has a value of 1, you need to check if the current collection object has a key of “apple” that has a value of 1 AND has a key of “bat” that has a value of 2. That is your condition for pushing.

I think the basic skeleton of what you have is right, you just need to work on these three lines:

    const newArr = Object.values(collection[i]);
    const joinedArr = newArr.concat(sourceArr)
    const condition = joinedArr.some((elem, index) => joinedArr.indexOf(elem) !== index)

That, and you need to not just deal with values. I don’t think you can do this by concating them. I don’t think some is going to be much use here - again, we don’t care if some of them match, we need them all to match. There is a prototype method for that that might work. Or you could write it out with a for loop.

See if that helps.

Thanks for your big comment, I wanted to answer before but I live in Israel and I think you’re from states so we have different hours.

I know the task asked for me to check for matching key/value.
But since this is an object and different memory If I recall I read about it, they will never match even if the value is the same, so I had really hard time thinking how I can do it.
The only thing that came up to my mind is getting the value of those keys, hence why I got the array approach solution. But I’ll see what I can do with your tips.

Also, is that really important to pseudo code before? is it like a better practice?

here you used in the console log an asterisk sign , what does it mean?

I’m actually in Spain - but it doesn’t matter. Answer when you can. Take time if you need.

But since this is an object and different memory If I recall I read about it, they will never match even if the value is the same…

That is true, if you are talking about reference types. The variable is storing a memory address (reference) so if the arrays are created separately:

const arr1 = [123]
const arr2 = [123]
arr1 === arr2 // false

It doesn’t matter that they contain the same values, they are different memory locations and that is what we are testing (even if it isn’t obvious).

FYI, if we copy the memory address, it is different:

const arr1 = [123]
const arr2 = arr1
arr1 === arr2 // true

The catch here is that there is only one array. If I change one, the other changes too. It would be like if I had my house address written down on a piece of paper, and I copied the address on another piece of paper. I didn’t create a new house, just a copy of the address.

But you are comparing the values, which in this case are primitive, numbers:

const arr1 = [123]
const arr2 = [123]
arr1 === arr2 // false
arr1[0] === arr2[0] // true

In that second test, they are resolving to numbers, which are primitives in JS so the variable does not store the reference (memory address) but the actual value. So, we are comparing the values, in this case, 123 is equal to 123.

Don’t feel bad if this is confusing - I have run into junior developer that still haven’t wrapped their head around that.

Also, is that really important to pseudo code before? is it like a better practice?

Is it a requirement? No. If I don’t need to pseudo code, I don’t.

When someone is learning to cook, they follow the recipe exactly. A master chef can just wing it.

Do I always pseudo code? No. If I don’t need to, if I can visualize it in my head, I don’t bother. But if I’m struggling with something, if it isn’t clear to me I grab my white board and start pseudo coding. It allows me to break the problem down into just the algorithm and not worry about code. It is one less thing to worry about it.

There are other advantages. Some job interviews are “white board” interviews where they may expect a pseudo code solution - or it would be easier for you. Also, you can discuss algorithms with people using different programming languages. I was at a coding meetup where three of us were trying to figure out an algorithm. We worked it out in pseudo code even though none of us knew the other’s coding language.

And again, I would say that if you can’t explain it in pseudo code, then you probably don’t understand the algorithm. Remember that pseudo code is not some defined language, you’re just explaining the idea. It doesn’t have to be written a certain way. It just has to be structured and clear. It gets easier with time.

here you used in the console log an asterisk sign , what does it mean?

That’s just something that I do with loops so I can tell what level I’m looping. The first loop gets 1, the loop inside that gets 3, the loop inside that gets 5 … It is not required, I just do it because it makes it clearer to me visually. Do whatever works for you.