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
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
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());
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);
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));