Skip to content

Instantly share code, notes, and snippets.

@mubasshir
Created June 24, 2022 15:58
Show Gist options
  • Save mubasshir/a179893a655f9782d156fe91d6ac50b0 to your computer and use it in GitHub Desktop.
Save mubasshir/a179893a655f9782d156fe91d6ac50b0 to your computer and use it in GitHub Desktop.
Merge/Zip Array of Objects with alternating elements
const posts = [{ id: 1, title: 'Post 1' }, { id: 2, title: 'Post 2' }, { id: 3, title: 'Post 3' }, { id: 4, title: 'Post 4' }];
const polls = [{ id: 1, question: 'Poll 1' }, { id: 2, question: 'Poll 2' }];
// get minimum length of both arrays
const minLength = Math.min(posts.length, polls.length);
// create
let postsAndPolls:any = [];
// loop through the array and fill it with the posts and polls
for (let i = 0; i < minLength; i++) {
// push ith post and ith poll to the array
postsAndPolls.push(posts[i], polls[i]);
}
// check if posts length is more than the minimum length
if (posts.length > minLength) {
// if so, push the rest of the array to the array
postsAndPolls.push(...posts.slice(minLength));
}
// check if polls length is more than the minimum length
if (polls.length > minLength) {
// if so, push the rest of the array to the array
postsAndPolls.push(...polls.slice(minLength));
}
// print the array
console.log(postsAndPolls);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment