Things JavaScript can do

This is a list of javascript ‘snippets’ I saved while working on projects recently. There’s ES6/7 stuff in there and some older JS too. I’m not advocating anything here as the best solution to any particular problem, just some mostly terse implementations of some common problems that might help others out.

Unique Array items

1
[...new Set([1, 2, 3, 3, 4, 5])] // [1, 2, 3, 4, 5]

Flatten 2D Array

1
[].concat(...a)

Array - Array

1
[1, 2, 3].filter(a => ![1, 4, 5].includes(a)); // [2, 3]

Remove falsey value from Array

1
[0, 1, 2,, null, false, '', 'foo'].filter(Boolean) // [1, 2, 'foo']

Array of random numbers…

1
Array(3).fill().map(Math.random) // [0.1354710466989566, 0.5319799814508592, 0.4037697346258513]

Pluck property from an Array of objects and remove falsey values

1
2
const arr = [{prop: 'foo'}, {prop: 'bar'}, {}];
arr.map(v => v.prop).filter(Boolean); // ['foo', 'bar']

Conditional object literal properties

You’ll need Babel or similar for this one at least at the moment. The Object rest spread operator is currently a stage 3 proposal.

1
2
3
4
5
6
7
const o = {
a: 1,
b: 2,
...true && {c: 3},
...false && {d: 4}
};
console.log(o) // {a: 1, b: 2, c: 3}

Required arguments

required() is called only if the bar is missing

1
2
3
4
5
6
function required() {
throw new Error('Missing parameter');
}
function foo(bar = required()) {
return true;
}

Concatenating arrays with properties

1
2
3
const foo = [1, 2, 3];
const bar = [4, 5, 6];
foo.prop = 'foo';

This won’t work

1
foo.concat(bar).prop; // undefined

This will

1
2
foo.push(...bar);
foo.prop; // foo

Exponentiation operator

old: Math.pow(10, 3)
new: 10 ** 3

Easier partial evaluation

Old:

1
2
3
4
function add(a, b) {
return a + b;
}
const add1 = add.bind(void 0, 1);

new:

1
2
3
4
function add(a, b) {
return a + b;
}
const add1 = a => add(a, 1);

Assigning to object properties and arrays via the rest operator:

1
2
[foo, ...bar] = ['a', 'b', 'c'];
console.log(foo, bar); // 'a', ['b', 'c']

And to an object property

1
2
3
const obj = {foo: '123'};
[foo, ...obj.bar] = ['a', 'b', 'c'];
console.log(foo, obj); // 'a', {foo: '123', bar: ['b', 'c']}