2

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"
  }
]

Please suggest me how can i achieve this.

Thanks a lot in advance

2
  • are the number of arrays fixed? Commented May 31, 2018 at 6:39
  • No .. it may vary Commented May 31, 2018 at 6:39

3 Answers 3

5

You can use .reduce() and .concat().

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

let result = data.reduce((a, c) => a.concat(c), []);

console.log(result);

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

Comments

2

You can use concat() and spread operator (...):

var arr = [
  [
    {
      "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 res = [].concat(...arr);
console.log(res);

Comments

2

You're just looking for a way to flatmap, which is easy with concat and spread:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.