Selects logo a praymentis.

I AM SELECT

Jan 08
2022
JavaScript can be short and fun. In this post I collect "one liners" that I use regularly in my code.

Handy ES6 one liners

Chunk Array

Chunk and array into several subarrays, the reverse algorithm to Array.prototype.flat()

const chunk = (arr,cz = 3) => [...Array(Math.ceil(arr.length / cz))]
    .map((_,i) => arr.slice(cz * i, cz * i + cz));
in:  [1,2,3,4,5,6,7]
out: [ [ 1,2,3 ], [ 4,5,6 ], [ 7 ] ]

chunk(arr) will convert arr into chunks of 3 items (the default value of the chunk size can be change chunk(arr, 5)). Use case: split a large number of API request (e.g. 1000 or more) into chunks that execute in parallel, save the result after each chunk is processed.

Array to Index (Object / Lookup)

Read more at about Building an indexed object from an array of objects in JavaScript in the dissection arcticle

const idx = lst.reduce((acc, item) => ({ ...acc, { [item.id]: item } }) , {})
in:  [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}]
out: {1: {id: 1, name: 'foo'}, 2: {id: 2, name: 'bar'}}

Use case build a simple index to find object in a sorted list faster than with mediaList.find(…) when you have to look up items often but also want to keep the sorting of the inital list.

Object keys to values

A reverse lookup for Objects.

const renameMapReverse = Object.entries(renameMap).reduce(
  (acc, [key, val]) => {...acc, { [val]: key }},
  {}
);
in: {
  byMe: 'created by me',
  otherOrga: 'from other organization',
  tutrials: 'tutrials',
};
out: {
  'created by me': 'byMe',
  'from other organization': 'otherOrga',
  tutrials: 'tutrials',
};

Filter duplicates

Remove duplicate entries from a list.

[...new Set([1, 2, 2, 3, 4, 6, 5 ,6])]
in:  [ 1, 2, 2, 3, 4, 6, 5 ,6 ]
out: [ 1, 2, 3, 4, 6, 5 ]

Range

Create an array with range of numbers.

const range = (start, end) => Array(end - start + 1)
    .fill()
    .map((_, idx) => start + idx)
› range(2,5)
[2, 3, 4, 5]

Zero padding

Add zeros (or any other character) to the left side of a string

const zeroPad = (num, size) => {
    const s = `000000000${num}`; 
    return s.substr(s.length - size); 
}
› zeroPad(4,3)
'004'

jQuery $() selector

Short-cut the CSS query selctor to $

const $ = document.querySelector
$('.classname').addEventListener('click', () => {})