Common elements of two lists
MediumMap and Set10 min
Write a function commonElements(listA, listB) that returns the elements that are in both lists: their intersection.
listAandlistBare arrays of strings. They can be empty and can have duplicates.- Return a new array with every common element once, even if it occurs several times in one or both lists.
- Order: the order of the first occurrence in
listA. - Case matters:
'ann'and'Ann'are different elements. - If there are no common elements, return an empty array.
A Set helps to check fast whether a value is in a list and to remember what is already in the result.
Examples
commonElements(['ann', 'bob', 'carl', 'dan'], ['dan', 'eve', 'bob'])Returns [ 'bob', 'dan' ]
commonElements(['ann', 'ann', 'bob'], ['ann'])Returns [ 'ann' ]
commonElements(['ann'], ['Ann'])Returns []
Asked at Ness Digital · Source
Loading the editor...
- Input
commonElements([ 'ann', 'bob', 'carl', 'dan' ], [ 'dan', 'eve', 'bob' ])Expected[ 'bob', 'dan' ] - Input
commonElements([ 'red', 'green' ], [ 'blue', 'green' ])Expected[ 'green' ] - Input
commonElements([ 'a', 'b' ], [ 'c', 'd' ])Expected[]
Hidden tests run on Submit