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 that exists in any of the two arrays 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.



JavaScript: Tips of the Day

Chunks an array into n smaller arrays

Example:

const tips_chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
}
console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4)); 

Output:

[[1,2],[3,4],[5,6],[7,8]]