I have an array of countries coming from the database.
Here are 2 examples of the input, and output I’m expecting:
// countries array (input)
['US','Canada','Mexico','North Korea','Korea','Germany'];
// expected output
['US','Canada','Mexico','North Korea','Germany'];
// countries array (input)
['North America','France','India','America'];
// expected output
['North America','France','India'];
I want to remove Korea
and America
from the respective arrays as I already have North Korea
and North America
corresponding to those elements.
I have tried includes()
method but it’s not working as it checks for the exact value.
How can I get the expected output?
3
Answers
Well, if later element is ‘included’ in previous element’s’, then it should be removed. Is it right? You can get an array of previous elements with
slice()
and check whether each element includes certain string withfilter()
like this.So you want to
filter()
the array of countries and remove a country ifsome()
other countryincludes()
the country name.whole !== part
is there is to prevent a country from matching against itself withwhole.includes(part)
.We can just use a reduce to perform that action where we check if other element includes the string. This assuming that the more especific comes later in the array, ie America will appear after north america.