7

i have the following array

let arr =   [
  [
    "[email protected]",
    "[email protected]"
  ],
  [
    "[email protected]",
    "[email protected]"
  ]
]

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

[
  [
    "[email protected]",
    "[email protected]",
    "[email protected]"
  ]  
]

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?

1
  • 2
    Is this .unique() method ES...DOESN'T-EXIST? Try using .writeCodeForMe() method. Commented Jul 14, 2019 at 11:50

2 Answers 2

16

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

Demo:

let arr =   [
  [
    "[email protected]",
    "[email protected]"
  ],
  [
    "[email protected]",
    "[email protected]"
  ]
]

let arr2 = [...new Set(arr.flat(1))];
console.log(arr2)

Sign up to request clarification or add additional context in comments.

Comments

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 = [
  [
    "[email protected]",
    "[email protected]"
  ],
  [
    "[email protected]",
    "[email protected]"
  ]
];

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 = [
  [
    "[email protected]",
    "[email protected]"
  ],
  [
    "[email protected]",
    "[email protected]"
  ]
];

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

1 Comment

It would really be great if all the Array methods would exist on Iterators ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.