7

i have the following array

let arr =   [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
]

i want get the unique values from this array. so im expecting my result to be like this

[
  [
    "s1@example.com",
    "s2@example.com",
    "s3@example.com"
  ]  
]

i have used array unique function but not able to get the result

var new_array = arr[0].concat(arr[1]);
var uniques = new_array.unique();

this worked if i have two index but how about for multiple index?

2 Answers2

15

You can use .flat() to flatten your array and then use Set to get its unique values.

Demo:

let arr =   [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
]

let arr2 = [...new Set(arr.flat(1))];
console.log(arr2)
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
0

You can take advantage of Set, which will automatically take care of duplicates, you can find more about Sets here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Since many solutions use flat along with Set, here is a solution using a function generator to actually flatten the array, yielding items as long as they are not arrays (otherwise, it recursively flatten them).

let arr = [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
];

function* flatten(array) {
  for (var item of array) {
    if (Array.isArray(item)) {
      yield* flatten(item)
    }
    else yield item;
  }
}

const set = [...new Set(flatten(arr))];
console.log('set is', set);

If you don't want to use Set, here is a solution without Set, by creating a new array and pushing items as long as they don't exist already.

let arr = [
  [
    "s1@example.com",
    "s2@example.com"
  ],
  [
    "s1@example.com",
    "s3@example.com"
  ]
];

function* flatten(array) {
  for (var item of array) {
    if (Array.isArray(item)) {
      yield* flatten(item)
    }
    else yield item;
  }
}

let unique = [];
for (const item of flatten(arr)) {
  if (unique.indexOf(item) === -1) unique.push(item);
}
console.log(unique);
briosheje
  • 7,356
  • 2
  • 32
  • 54