panzerdp / dmitripavlutin.com-comments

7 stars 0 forks source link

javascript-merge-arrays/ #113

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

3 Ways to Merge Arrays in JavaScript

How to merge arrays in JavaScript using spread operator, array.concat() and array.push().

https://dmitripavlutin.com/javascript-merge-arrays/

vipinc007 commented 3 years ago

Wow Super. its great to learn all these new options to merge array. I was not aware of "[].concat" until I saw this post. Thanks for writing this informative article.

MaryJJ commented 3 years ago

Girls are also superheroes or villains :). I love your blog

const heroes = ['Batman', 'Superman'];
const villains = ['Joker', 'Bane'];
const heroines = ['Superwoman', 'Captain Marvel'];
heroes.push(...[...villains, ...heroines]);
0xDAEF0F commented 3 years ago

its a shallow copy tho... if u have nested objects/arrays they will still be referenced in memory... Maybe next article about the proper way to mutate nested objects??? that things trips me up everytime man! love your articles btw!

panzerdp commented 3 years ago

Girls are also superheroes or villains :). I love your blog

const heroes = ['Batman', 'Superman'];
const villains = ['Joker', 'Bane'];
const heroines = ['Superwoman', 'Captain Marvel'];
heroes.push(...[...villains, ...heroines]);

Looks good @MaryJJ :).

leolanese commented 3 years ago

The "best" option, at least this is what I use all the time, is the immutable merge of arrays using the spread operator, but I also want to add this extra option ways to merge arrays in JS:

const heroes = ['Batman', 'Superman'];
const villains = ['Joker', 'Bane'];

Array.prototype.push.apply(heroes, villains);
heroes; // ['Batman', 'Superman', 'Joker', 'Bane']
1ucasdev commented 1 year ago

Thanks for the great lesson! Best wishes to you!

panzerdp commented 1 year ago

@1ucasdev Thanks. 👍

kubraguler commented 8 months ago

This is a great article! Thanks @panzerdp