-1

I'm in a situation in which for me it is vital to add two arrays together and create a new array which does not have the memebers of tow arrays which are the same being added to the final array as multiple members but rather just one,I just want to have one memeber as the representive of those identical members from two arrays in the final array, not having them as multiple memebers in the final array,I tried concat() and it did exactly what I don't want. How can I do this, guys? like:

let arrayone = [2,4,6];
let arraytwo = [2,4,7];

I want the final array to be

finalarray = [2,4,6,7]

but concat() gives me

final array [2,4,6,2,4,7]

This was just for more clarification, the members of my arrays are objects.

AbeIsWatching
  • 159
  • 1
  • 11
  • Could you write a code with examples of such arrays? Does it mean, that you just want to have a combination of two arrays with unique members? – Buszmen Feb 10 '20 at 21:13
  • First, don't assume the person who comment is the same who downvote you. Second, example of code will help as it matters if array members are objects or not. And last but not least - think more and search as it's been answered before: https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – Buszmen Feb 10 '20 at 21:26

1 Answers1

0

In set theory, this is called the "union". There are a number of ways to do this in JavaScript. If the arrays only contain primitive values, you can simply build a Set out of them, and then spread back into an array:

const firstArray = [1, 2, 3]
const secondArray = [3, 4, 5]
const union = [...new Set([...firstArray, ...secondArray])] // [1, 2, 3, 4, 5]

The Set constructor ensures that no duplicate values are added to the set. If the values of the arrays are NOT primitives (i.e. objects or something else), you'll need to use some other means of iteration to achieve a union. Here is a good example of deriving the union of two arrays of objects.

djfdev
  • 5,747
  • 3
  • 19
  • 38