-2
const names = ["Daniel", "Lucas", "Gwen", "Henry", "Jasper"];
const random = ["hi", "Lucas", "apple", "banana", "Jasper", "hello", "meow"];

What I want here is to compare names and random, if there are any duplicates in random, remove them and have an outcome like this.

const newArr = ["hi", "apple", "banana", "hello", "meow"]

How can I do that?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Happy1234
  • 537
  • 3
  • 15

3 Answers3

2

const names = ["Daniel", "Lucas", "Gwen", "Henry", "Jasper"];
const random = ["hi", "Lucas", "apple", "banana", "Jasper", "hello", "meow"];
const result = random.filter(name => !names.includes(name))
console.log(result)
Konrad
  • 21,590
  • 4
  • 28
  • 64
1

It's a simple filter call

const newArr = random.filter(elem => !names.includes(elem))
1

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.

KernelDeimos
  • 503
  • 4
  • 12