1

I count with the following example array

let animals = ['dog', 'cat', 'egypt cat', 'fish', 'golden fish'] 

the basic idea is get to the following result removing the elements which are included on the other strings

['dog', 'egypt cat', 'golden fish'] 

My approach was detect which are included iterating twice on the array and comparing the values

let arr2 = []
arr.forEach((el, i) => {
    arr.forEach((sub_el, z) => {
        if (i != z && sub_el.includes(el)) {
          arr2.push(el)
        }
      })
    })

then filter the array with those matched values. Anyone has a simplest solution?

2

1 Answer 1

1

You need to itterate the array again and then check any string.

This approach minimizes the iteration by a short circuit on found of a matching string.

let animals = ['dog', 'cat', 'egypt cat', 'fish', 'golden fish'],
    result = animals.filter((s, i, a) => !a.some((t, j) => i !== j && t.includes(s)));

console.log(result);

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

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.