karo-s
karo-s

Reputation: 414

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)

Upvotes: 1

Views: 61

Answers (3)

Nitheesh
Nitheesh

Reputation: 20016

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);

Upvotes: 1

Alan Omar
Alan Omar

Reputation: 4227

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)

Upvotes: 0

Mamun
Mamun

Reputation: 68933

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);

Upvotes: 3

Related Questions