1

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)
2
  • What you understand is correct, can you show us an attempt at a solution? Commented Sep 17, 2021 at 10:43
  • 1
    I added my attempt. Commented Sep 17, 2021 at 10:46

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

@karolina-szlenk, you are most welcome:)
1

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

1 Comment

The author wants to filter the first array by the contents of the second array, not just filter away values after the :.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.