Sep 9, 2021 JavaScript
How to split an array into chunks in JavaScript

In this Article we will go through how to split an array into chunks only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const chunk = (arr, size) => arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);

Sep 9, 2021 JavaScript
How to swap the rows and columns of a matrix in JavaScript

In this Article we will go through how to swap the rows and columns of a matrix only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const transpose = matrix => matrix[0].map((col, i) => matrix.map(row => row[i]));

Sep 9, 2021 JavaScript
How to swap two array items in JavaScript

In this Article we will go through how to swap two array items only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const swapItems = (a, i, j) => a[i] && a[j] && [...a.slice(0, i), a[j], ...a.slice(i + 1, j), a[i], ...a.slice(j + 1)] || a;

Sep 9, 2021 JavaScript
How to unzip an array of arrays in JavaScript

In this Article we will go through how to unzip an array of arrays only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const unzip = arr => arr.reduce((acc, c) => (c.forEach((v, i) => acc[i].push(v)), acc), Array.from({ length: Math.max(...arr.map(a => a.length)) }, (_) => []));

Sep 9, 2021 JavaScript
How to zip multiple arrays in JavaScript

In this Article we will go through how to zip multiple arrays only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const zip = (...arr) => Array.from({ length: Math.max(...arr.map(a => a.length)) }, (_, i) => arr.map(a => a[i]));

Sep 9, 2021 JavaScript
How to add am pm suffix to an hour in JavaScript

In this Article we will go through how to add am pm suffix to an hour only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const suffixAmPm = h => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;