Home > Blockchain >  Compare two arrays and if match pass to object
Compare two arrays and if match pass to object

Time:06-11

The function has test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value.

    function objOfMatches(arr1, arr2, callback){
let obj ={};
let newArr1 = arr1.toString();
newArr1 = callback(newArr1);
newArr1 = newArr1.split(",");

arr1.forEach(el=>{
  if((callback(newArr1) === arr2[el])) obj[arr1[el]] = arr2[el];
});

return obj;
}

The problem I got is that when I call function like this:

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); };
console.log(objOfMatches(arr1, arr2, uppercaser));

It gives an error (Type Error on line 18: str.toUpperCase is not a function).

However, it is working perfectly fine if used with a FOR loop instead of .forEach like this:

for(let i=0; i<arr1.length; i  ){
  if(callback(arr1[i]) === arr2[i]){       
    obj[arr1[i]] = arr2[i];
  }
}

Can someone please explain to me in a JS beginner level language why it does not work?

CodePudding user response:

In short, newArr1 has become an array when you called .toUpperCase(), hence the TypeError. Let's take a closer look at your function:

function objOfMatches(arr1, arr2, callback) {
  let obj = {};
  let newArr1 = arr1.toString(); // string
  newArr1 = callback(newArr1); // string
  newArr1 = newArr1.split(','); // array

  arr1.forEach((el) => {
    if (callback(newArr1) === arr2[el]) { // Error, newArr1 is an array and doesn't have the method .toUpperCase() 
      obj[arr1[el]] = arr2[el];
    }
  });

  return obj;
}

Not to mention, the logic of your function is wrong. Based on your description, it should be more like this:

function objOfMatches(arr1, arr2, callback) {
  let obj = {};

  arr1.forEach((el, index) => {
    if (callback(el) === arr2[index]) {
      obj[el] = arr2[index]; // E.g. { 'hi': 'HI' }
    }
  });

  return obj;
}

The for loop version is actually correct, so it works:

function objOfMatches(arr1, arr2, callback) {
  let obj = {};

  for(let i=0; i<arr1.length; i  ){
    if(callback(arr1[i]) === arr2[i]){ // Correct, arr1 is an array of string so each string will have .toUpperCase()  
      obj[arr1[i]] = arr2[i];
    }
  }

  return obj;
}
  • Related