-2

I have a set of arrays

set1 = [[1,1,2,5],[4,3,5,9],[7,8,9,4,1]]

and I want to covert it to a single set so there is no duplicates

Andy
  • 61,948
  • 13
  • 68
  • 95
Chad
  • 3
  • 3

3 Answers3

1

Use the flat method to combine the sub-arrays into one big array, and then create a set out of it to remove duplicates:

new Set(set1.flat());
Eldar B.
  • 1,097
  • 9
  • 22
1

You have an array of arrays. A set in JavaScript is a specific JS object type. But you can use a set to create a de-duped array.

First flatten the nested array, and then pass that as an argument into a new Set().

If you need an array again you can spread the set out.

const arr = [[1,1,2,5],[4,3,5,9],[7,8,9,4,1]];

const set = new Set(arr.flat());

const newArr = [...set];

console.log(newArr);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

You can use flat() first then a function to remove duplicate elements from the array like this

const set1 = [
  [1, 1, 2, 5],
  [4, 3, 5, 9],
  [7, 8, 9, 4, 1]
];

const result = set1.flat();

 function removeDuplicates(arr) {
   return arr.filter((item,index) => arr.indexOf(item) === index);
 }

console.log(removeDuplicates(result));
Chris G
  • 1,598
  • 1
  • 6
  • 18
  • Your approach for removing duplicates work but you can also just create a Set from that array, which is a slightly simpler solution :) – Eldar B. Oct 01 '22 at 15:32
  • True, but hey you always learn something new everyday, thanx for the tip – Chris G Oct 01 '22 at 15:33