Are array of numbers equal - JavaScript

We need to write a JavaScript function that takes in two arrays of numbers and checks for their equality based on specific criteria.

The arrays will be considered equal if:

  • They contain the same elements and in the same order.
  • The product of all the elements of the first array and second array is equal.

Example Arrays

The first array of numbers:

const first = [3, 5, 6, 7, 7];

The second array of numbers:

const second = [7, 5, 3, 7, 6];

Solution

Here's a corrected implementation that properly checks both conditions:

const first = [3, 5, 6, 7, 7];
const second = [7, 5, 3, 7, 6];

const isEqual = (first, second) => {
    // First check: arrays must have same length
    if (first.length !== second.length) {
        return false;
    }
    
    // Second check: products must be equal
    const prodFirst = first.reduce((acc, val) => acc * val);
    const prodSecond = second.reduce((acc, val) => acc * val);
    
    if (prodFirst !== prodSecond) {
        return false;
    }
    
    // Third check: elements in same order
    for (let i = 0; i 

false

Why the Result is False

Let's analyze why these arrays are not equal:

const first = [3, 5, 6, 7, 7];
const second = [7, 5, 3, 7, 6];

// Check products
const prodFirst = first.reduce((acc, val) => acc * val);
const prodSecond = second.reduce((acc, val) => acc * val);

console.log("Product of first:", prodFirst);   // 4410
console.log("Product of second:", prodSecond); // 4410
console.log("Products equal:", prodFirst === prodSecond);

// Check element order
console.log("Same order:", JSON.stringify(first) === JSON.stringify(second));
Product of first: 4410
Product of second: 4410
Products equal: true
Same order: false

Testing with Equal Arrays

Here's an example where arrays would be considered equal:

const arr1 = [2, 3, 4];
const arr2 = [2, 3, 4];

const isEqual = (first, second) => {
    if (first.length !== second.length) return false;
    
    const prodFirst = first.reduce((acc, val) => acc * val);
    const prodSecond = second.reduce((acc, val) => acc * val);
    
    if (prodFirst !== prodSecond) return false;
    
    for (let i = 0; i 

true

Conclusion

The function checks both product equality and element order. Arrays must satisfy both conditions to be considered equal under these specific criteria.

Updated on: 2026-03-15T23:18:59+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements