1 | initial version |
One way to remove duplicated objects within a nested array is to use the filter()
method in combination with the indexOf()
method.
The filter()
method creates a new array with all elements that pass the test implemented by the provided function, while the indexOf()
method returns the first index at which a given element can be found in the array.
Here's an example code snippet that removes duplicated objects within a nested array:
const nestedArray = [[1, 2], [1, 2], [2, 3], [4, 5], [4, 5]];
const filteredArray = nestedArray.filter((arr, index) =>
index === nestedArray.findIndex(a => a.toString() === arr.toString())
);
console.log(filteredArray);// [[1, 2], [2, 3], [4, 5]]
In this example, the filter()
method uses the findIndex()
method to find the first occurrence of each array (by comparing their string representations), and only keeps the elements with unique indices. The resulting filteredArray
contains only the distinct nested arrays.