Joaquin Diaz
Joaquin Diaz

Reputation: 175

Find if a string from an array is included on another string from the same array

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?

Upvotes: 1

Views: 48

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

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

Upvotes: 1

Related Questions