Skip to content

Instantly share code, notes, and snippets.

@MaraAlexa
Last active April 29, 2017 09:21
Show Gist options
  • Save MaraAlexa/2b3b7df8533c7f93df43535807504077 to your computer and use it in GitHub Desktop.
Save MaraAlexa/2b3b7df8533c7f93df43535807504077 to your computer and use it in GitHub Desktop.
Use .concat to Add Values to an Array
// with .concat you can Add values(of mixed types) to an Array
var items = [1,2];
var newItems = items.concat(3,4,'string', undefined);
console.log(newItems); // [1, 2, 3, 4, 'string', undefined]
// .concat can also take in other arrays
var newArrayItems = items.concat([3,4], [5,6,7], 8,9);
console.log(newArrayItems); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Practical USE CASE:
var people = [
{
name: 'Shane'
},
{
name: 'Sally'
}
];
var people2 = [
{
name: 'Simon'
},
{
name: 'Ben'
}
];
// Combine all the proprieties from the arrays above
// BAD PRACTICE
people.forEach(function(person){
console.log(person.name);
})
people1.forEach(function(person){
console.log(person.name);
})
// GOOD PRACTICE
people.concat(people2).forEach(function(person){
console.log(person.name); /* "Shane"
"Sally"
"Simon"
"Ben" */
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment