Skip to content

Instantly share code, notes, and snippets.

@jherr
Created March 21, 2020 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jherr/f8cbd76ced21d3aa73f7d2a903efd5c9 to your computer and use it in GitHub Desktop.
Save jherr/f8cbd76ced21d3aa73f7d2a903efd5c9 to your computer and use it in GitHub Desktop.
ES6 arrays
// Creating arrays
const a1 = [1,2,3];
const a2 = Array.from([2,3,4]);
const a3 = new Array(20).fill(0).map((n,x) => x + 1);
// Length
a3.length;
// Destructuring arrays
const [v1, v2, v3] = a1;
// Concatenating arrays
const a4 = [...a1, ...a2];
a1.concat(a2)
// Join
a4.join(' ')
a4.join('')
// Iteration
const names = ['A', 'B', 'C'];
for(let i1 in names) {
console.log(i1);
}
for(let i1 of names) {
console.log(i1);
}
names.forEach((name) => {
console.log(name)
});
names.forEach((name, index) => {
console.log(index)
});
// map
names.map(n => n.toUpperCase());
names.map((n, i) => i);
// filter
names.filter(n => n.indexOf('ack') > -1);
// reduce
a1.reduce((a, n) => a + n, 0);
a1.reduce((a, n) => a - n, 0);
names.reduce((a, n) => a + n, '');
names.reduceRight((a, n) => a + n, '');
// flat
const a5 = [a1, a2]
a5.flat()
const a6 = [ [ a1 ], [ a2 ] ];
a6.flat(2)
// flatMap
const data = [ { name: 'Bill' }, { name: 'Ted' } ]
data.flatMap(({ name }) => name);
// slice
names.slice()
names.slice(1)
names.slice(0, 1)
// find, findexIndex, indexOf, includes, lastIndexOf
names.find(n => n === 'B')
names.findIndex(n => n === 'B')
names.includes('B')
names.indexOf('C')
const a7 = ['a', 'c', 'a']
a7.indexOf('a')
a7.lastIndexOf('a')
// some, every
a1.some(n => n > 1)
a1.every(n => n > 1)
// push, pop, shift, unshift, splice
names.push('Mo');
names
names.pop();
names
names.unshift('First')
names
names.shift()
names
// sort and reverse
names.reverse();
names.sort();
// toString
names.toString()
// keys and values
Array.from(names.keys())
Array.from(names.values())
// Chaining
a4.filter(n => n > 2).map(n => n * 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment