The code provided will generate the same output as shown, but it is tailored for two-dimensional arrays like the one in your example:
const arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5']];
const arr2 = Array
.from(
new Map(
arr.reverse()
)
)
.reverse()
;
console.log(JSON.stringify(arr2));
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"]]
If Object.fromEntries
is available, an alternative implementation could be:
const arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5']];
const arr2 = Object
.entries(
Object.fromEntries(
arr.reverse()
)
)
.reverse()
;
console.log(JSON.stringify(arr2));
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"]]
However, this might be less performant compared to the previous method.
If you want to skip repeated values at any position within the inner array, additional steps are needed:
In the input example, 'item 5' is repeated but is ignored because its first occurrence is with 'item 1'.
Adding a new element like ['item 7', 'item 6'] would pass in the previous example:
// ...
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"],["item 7","item 6"]]
To account for all elements and scan all sub-elements, you can use the following approach:
const arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5'], ['item 7','item 6']];
const seen = new Set();
const arr2 = arr
.filter(function hasRepetition(items) {
if ( // Repetition found
1 + items.findIndex(itm=>seen.has(itm))
) return false;
items.map(seen.add, seen);
return true;
})
;
console.log(JSON.stringify(arr2));
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"]]
This solution also works for arrays of any dimensions.
Edit:
This solution can handle arrays with any length in both dimensions but may require adjustments for more than two dimensions.