Objofmatches problem

Can someone help me understand the correct way to implement object literals into algorithms? I am trying to solve a problem where a function takes two arrays and a callback function and creates a new object where if callback(array1) === array2, it returns a new object where {array1 : array2}. I think I now logic just am so lost on implementation. Here is my code:

//construct function that accepts two arrays, callback
const objOfMatches = (array1, array2, callback) => {
  //create empty objOfMatches
  const matches = new Object();
  //loop through array1[i] and check if matches with array2[i]
  for (let i = 0; i < array1.length; i++) { 
    //if callback(array1) === array2
		//create new key, array1[i] : array2[i]
    if (callback(array1[i]) === array2) {
        matches.match = array1[i]
        function objectman (array2) {
      this.matches = array2
    	}
    }
  }
  return matches
}

Any help would be majestic!

1 Like

You can’t compare two objects (including arrays) with the equality operator. === will only be true if both variables are referencing the same memory entity. If you want to check whether arrays are equivalent you need to check the values they contain.

1 Like

What Ariel said, or use JSON.stringify():

const object1 = {'test':[1,2,3]};
const object2 = {'test':[1,2,3]};

console.log(object1 === object2) // false
console.log(JSON.stringify(object1) === JSON.stringify(object2)) // true
1 Like
  //create empty objOfMatches
  const matches = {};
  //loop through array1[i] and check if matches with array2[i]
  for (let i = 0; i < array1.length; i++) { 
    //if callback(array1) === array2
		//create new key, array1[i] : array2[i]
    if (callback(array1[i]) === array2[i]) {
        matches.array1 = array2[i]    
    }
  }
  return matches
}

this is all i’ve got so far. it’s returning {array1 : HELLO} because I’m not sure how to set a new object key every loop. It seems so close but I am lost. any other hints on how to implement stringify or something like that would be greatly appreciated

1 Like