0

I have to merge chunk of arrays into single array with array of objects in Angularjs.

my input array will be like:

[
  [
    {
      "title": "asd",
      "description": "asd"
    },
    {
      "title": "asz",
      "description": "sd"
    }
  ],
  [
    {
      "title": "ws",
      "description": "sd"
    },
    {
      "title": "re",
      "description": "sd"
    }
  ],
  [
    {
      "title": "32",
      "description": "xxs"
    },
    {
      "title": "xxc",
      "description": "11"
    }
  ]
]

The above input array should be save like array of objects like below

[
  {
    "title": "asd",
    "description": "asd"
  },
  {
    "title": "asz",
    "description": "sd"
  },
  {
    "title": "ws",
    "description": "sd"
  },
  {
    "title": "re",
    "description": "sd"
  },
  {
    "title": "32",
    "description": "xxs"
  },
  {
    "title": "xxc",
    "description": "11"
  }
]

I did this like below,

const input=[[{"title":"asd","description":"asd"},{"title":"asz","description":"sd"}],[{"title":"ws","description":"sd"},{"title":"re","description":"sd"}],[{"title":"32","description":"xxs"},{"title":"xxc","description":"11"}]]
const output = [].concat(...input);
console.log(output);

But it is in ES6 i think. Can u help me out with ES5 implementation?

Thanks in advance

user6250770
  • 680
  • 2
  • 10
  • 25
  • Paste your ES6 code into the babel REPL and see if you like the ES5 code it creates :-) --> https://babeljs.io/repl – skovmand Jun 18 '18 at 06:09
  • you can check various answers here including ES5 https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items – Sajeetharan Jun 18 '18 at 06:10

1 Answers1

4

You can apply the input array of arrays to concat:

var input = [
  [
    {
      "title": "asd",
      "description": "asd"
    },
    {
      "title": "asz",
      "description": "sd"
    }
  ],
  [
    {
      "title": "ws",
      "description": "sd"
    },
    {
      "title": "re",
      "description": "sd"
    }
  ],
  [
    {
      "title": "32",
      "description": "xxs"
    },
    {
      "title": "xxc",
      "description": "11"
    }
  ]
];

var result = Array.prototype.concat.apply([], input);
console.log(result);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320