Reputation: 36229
Let's say I have a 2D array:
const matrixRegular = [
['a', 'b', 'c'],
['e', 'f', 'g'],
];
Let's say I want to verify that every row in this matrix has the same length, so the example above is a valid matrix, but the example below is not:
const matrixIrregular = [
['a', 'b', 'c'],
['e', 'f']
];
What's a clean/elegant way of doing it? This is the one-liner I have:
const isRegularMatrix = matrix => new Set(data.map(row => row.length)).size === 1
Convert the matrix to an array of just row length, then use Set
to ensure every element is a duplicate (same length), hence it comes out with size 1.
Upvotes: 2
Views: 617
Reputation: 36584
You can use every()
and compare length
of each array with the length of the first.
const isRegularMatrix = matrix => matrix.every(x => x.length === matrix[0].length)
Upvotes: 13