Alphabet Array JavaScript
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
console.log(alphabet);
// outputs: ['a', 'b', 'c', ... 'z']
Create an array of the alphabet.
Splitting a string with an empty string results in each character being placed into a slot in the new array.
Merge Collection (array of objects)
const collection = [
{ name: 'Joe' },
{ age: 31 },
{ job: 'programmer' }
];
const merged = Object.assign({}, ...collection);
console.log(merged);
Combine (“assign”) entire array of objects.
Saw this here… figured it was worth a quick post.
Guess the semi-golf
a=3217+'';a=[a];console.log(a[0][2])
Try and guess what would be logged here…
Array Range from 1
Object.assign(Number.prototype, {
*[Symbol.iterator]() {
for (let i = this; i--;)
yield this - i;
}
});
console.log([...3]);
I saw this on twitter a little while back. Tweet was from James Padolsey. A fun trick, the thread is pretty entertaining.
Random Value From Array
const modes = ['walk', 'run', 'hide', 'jump', 'dance'];
const randomMode = modes[Math.floor(modes.length * Math.random())];
console.log(randomMode);
// turn it into a function:
function randomChoice(arr) {
return arr[Math.floor(arr.length * Math.random())];
}
const colors = ['red', 'green', 'blue', 'black', 'white'] ;
console.log(randomChoice(colors));
console.log(randomChoice(modes));
Grab a random value from an array.