0

How to merge or union the array of array in angular

const b: any = [];
b.push(
  [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-21 08:08:00" }
  ],
  [{ date: "2019-12-20 08:08:00" }, { date: "2019-10-20 08:08:00" }],
  [{ date: "2019-12-20 08:08:00" }, { date: "2019-12-30 08:08:00" }]
);
uniq(flatten(b, true), true, item => item.date); //error here

error:Expected 1 arguments, but got 3.

and remove the duplicate using the lodash uniqBy.

expected output:

[
    "2019-12-21 08:08:00",
    "2019-12-20 08:08:00",
    "2019-12-30 08:08:00"
]
ABC
  • 752
  • 4
  • 17
  • 40
  • Does this answer your question? [Merge/flatten an array of arrays](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) – Armen Stepanyan Jan 22 '20 at 06:49

2 Answers2

1

You can use Underscore - uniq and flatten to achieve this.

const b: any = []; b.push(   [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-21 08:08:00" }   
   ],
   [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-10-20 08:08:00" }
   ],
   [
    { date: "2019-12-20 08:08:00" }, 
    { date: "2019-12-30 08:08:00" }
   ] );
_.uniq(_.flatten(b, true), true, item => item.date)

Result:

[{date:"2019-12-20 08:08:00"},
{date:"2019-12-21 08:08:00"},
{date:"2019-10-20 08:08:00"},
{date:"2019-12-30 08:08:00"}]

With lodash, below is the way

_.uniqBy(_.flatten(b, item => item.date), 'date')

Paritosh
  • 11,144
  • 5
  • 56
  • 74
1

We can use vanilla JavaScript. So what we need is:

  • Map to get only unique items from array
  • flatMap method to flat array
  • Array.from to create array from Map collection

So code looks like this:

const result = new Map(b.flatMap(s => s).map(a => [a.date]));
let uniques = Array.from(result.keys());

An example:

const b = [];
b.push(
  [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-20 08:08:00" },
    { date: "2019-12-21 08:08:00" }
  ],
  [
    { date: "2019-12-20 08:08:00" },
    { date: "2019-10-20 08:08:00" }
  ],
  [{ date: "2019-12-20 08:08:00" },
  { date: "2019-12-30 08:08:00" }]
);

const result = new Map(b.flatMap(s => s).map(a => [a.date]));
console.log(Array.from(result.keys()));
StepUp
  • 36,391
  • 15
  • 88
  • 148