Imagine you have a 2D array like this:
const matrixRegular = [
['a', 'b', 'c'],
['e', 'f', 'g'],
];
Now, let's think about how we can check if every row in this matrix has the same length. For example, the matrix above is valid, but the one below is not:
const matrixIrregular = [
['a', 'b', 'c'],
['e', 'f']
];
Is there a neat and elegant way to accomplish this? Here's a one-liner that does the trick:
const isRegularMatrix = matrix => new Set(data.map(row => row.length)).size === 1
Simply convert the matrix into an array containing just the row lengths, and then use a Set
to check if all elements are duplicates (i.e., have the same length), resulting in a size of 1.