As suggested by other answers, you can use the filter method to remove duplicates like this:
const newArr = random.filter(name => ! names.includes(name));
For the number of values you presented in your example, this should be perfectly sufficient. If you have a very large number of values it may not be.
The time complexity of this algorithm is O(n^2) (assuming a similar size for both lists). For each iteration over a value in random
, every value in names
is subsequently checked by includes
.
For a very large number of values, consider using Map
.
const names = ["Daniel", "Lucas", "Gwen", "Henry", "Jasper"];
const random = ["hi", "Lucas", "apple", "banana", "Jasper", "hello", "meow"];
const namesMap = new Map();
for ( const name of names ) namesMap.set(name, true);
const newArr = [];
for ( const rand of random ) {
if ( namesMap.has(rand) ) continue;
newArr.push(rand);
}
Although there is an additional loop, both loops are O(n) time complexity, so you get O(2n) which is considered equivalent to O(n).
Notice this inhibits readability. That's why it's only worth doing for a large number of values.