- Array length comparison
- Checking values without considering types using double equals
const arrA = [4, 4];
const arrB = [4, 4];
function compareArrays(arrA, arrB) {
if (arrA.length != arrB.length) {
return false;
}
let areEqual = arrA.every((valueA, indexA) => valueA == arrB[indexA]);
return areEqual;
}
console.log(compareArrays(arrA, arrB))
However, the arrays could contain object values, so a function is needed to check equality for both primitive and object types.
For better solutions, refer to reliable sources like lodash.
https://github.com/lodash/lodash/blob/master/.internal/equalArrays.js
Additional information.
import { compareArrays } from './compareArrays';
describe('compareArrays', () => {
test('number tuples', () => {
const arrA: [number, number] = [4, 4];
const arrB: [number, number] = [4, 4];
expect(compareArrays(arrA, arrB)).toBe(true);
});
test('primitive tuples without objects', () => {
const arrA: [boolean, number] = [false, 4];
const arrB: [boolean, number] = [true, 4];
expect(compareArrays(arrA, arrB)).toBe(false);
});
test('primitive tuples without objects', () => {
const arrA: [string, number] = ['almel', 4];
const arrB: [string, number] = ['shun', 4];
expect(compareArrays(arrA, arrB)).toBe(false);
});
test('primitive tuples without objects', () => {
const arrA: [string, number] = ['almel', 1];
const arrB: [string, boolean] = ['almel', true];
expect(compareArrays(arrA, arrB)).toBe(true); // because of double equals, number and boolean are considered equal
});
test('Double equals', () => {
const arrA: [number, number] = [4, 4];
const arrB: [number, number] = [4, 4];
expect(arrA == arrB).toBe(false);
});
});
I conducted tests using ts-jest, and all tests passed successfully.
In the world of JavaScript, there are no tuple types; what we have are arrays.