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
}
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.
//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