Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
Compare two arrays and if match pass to object

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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;
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda