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

206
Visualizações
How to create a new array from another one?

I have one array:

const animals = ['cat', 'dog', 'cow', 'horse']

And second one:

const animalsWithNames = ['cat:mik', 'dog', 'horse:lucy']

And I need to create a function that gives me in a result a third array:

const result = ['cat', 'dog', 'horse']

So, as well I understad I have to map first array and check by function. If piece of string exist in first array's item it should be in the result one. Am I right? Please about tips or proposal solutions.

My attempt:

const checkStr = str => animalsWithNames.forEach(el => {
        if (el.substring(0, str.length) === str) {
            return str
        }
    })

const result = animals.map(el => checkStr(el))
console.log(result)
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can try using Array.prototype.filter() and Array.prototype.some() like the following way:

const animals = ['cat', 'dog', 'cow', 'horse'];
const animalsWithNames = ['cat:mik', 'dog', 'horse:lucy'];
const result = animals.filter(a => animalsWithNames.some(an => an.split(':')[0] == a));
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Just use Array.reduce with looping through first array and checking the nodes is present in second.

const animals = ['cat', 'dog', 'cow', 'horse'];
const animalsWithNames = ['cat:mik', 'dog', 'horse:lucy'];
const result = animals.reduce((acc, curr) => {
  const node = animalsWithNames.find(item => item.indexOf(curr) > -1);
  if (node) {
    acc.push(curr)
  }
  return acc;
}, []);
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

const animals = ['cat', 'dog', 'cow', 'horse']
const animalsWithNames = ['cat:mik', 'dog', 'horse:lucy']

const names = animalsWithNames.map(e => e.split(":")[0])
const result = names.filter(e => animals.includes(e))

console.log(result)

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