w3resource

JavaScript: Get every element that exists in any of the two arrays once

JavaScript fundamental (ES6 Syntax): Exercise-110 with Solution

Write a JavaScript program to get every element in any of the two arrays at once.

Note: Create a Set with all values of a and b and convert to an array.

  • Create a new Set() with all values of a and b and convert it to an array.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const union = (a, b) => Array.from(new Set([...a, ...b]));
console.log(union([1, 2, 3], [4, 3, 2]));
console.log(union([1, 2, 3], [1, 2, 3]));

Sample Output:

[1,2,3,4]
[1,2,3]

Pictorial Presentation:

JavaScript Fundamental: Get every element that exists in any of the two arrays once.

Flowchart:

flowchart: Get every element that exists in any of the two arrays once

Live Demo:

See the Pen javascript-basic-exercise-110-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get the nth element of an given array.
Next: Write a JavaScript program to build an array, using an iterator function and an initial seed value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.