Get the total number of same objects in JavaScript

When working with arrays of objects in JavaScript, you often need to count how many objects share the same property values. This is useful for analyzing data like flight routes, user preferences, or categorizing items.

Suppose we have an array of objects describing flight routes:

const routes = [
    {
        flyFrom: "CDG",
        flyTo: "DUB",
        return: 0,
    },
    {
        flyFrom: "DUB",
        flyTo: "SXF",
        return: 0,
    },
    {
        flyFrom: "SFX",
        flyTo: "CDG",
        return: 1,
    }
];

We need to count how many times return: 0 and return: 1 appear, then display appropriate messages based on the flight type.

Method 1: Using forEach with Object Counting

const routes = [
    {
        flyFrom: "CDG",
        flyTo: "DUB",
        return: 0,
    },
    {
        flyFrom: "DUB",
        flyTo: "SXF",
        return: 0,
    },
    {
        flyFrom: "SFX",
        flyTo: "CDG",
        return: 1,
    }
];

const displaySimilar = arr => {
    const count = {};
    
    // Count occurrences of each return value
    arr.forEach(el => {
        count[el.return] = (count[el.return] || 0) + 1;
    });
    
    // Display results based on counts
    Object.keys(count).forEach(key => {
        for(let i = 0; i < count[key]; i++){
            if(key === '0'){
                console.log('1 Stop');
            }
            else if(key === '1'){
                console.log('Non-stop');
            }
        }
    });
};

displaySimilar(routes);
1 Stop
1 Stop
Non-stop

Method 2: Using reduce for Counting

const countAndDisplay = (arr) => {
    const counts = arr.reduce((acc, route) => {
        acc[route.return] = (acc[route.return] || 0) + 1;
        return acc;
    }, {});
    
    console.log("Count summary:");
    Object.entries(counts).forEach(([key, count]) => {
        const type = key === '0' ? '1 Stop' : 'Non-stop';
        console.log(`${type}: ${count} occurrences`);
    });
};

countAndDisplay(routes);
Count summary:
1 Stop: 2 occurrences
Non-stop: 1 occurrences

Method 3: Using filter for Direct Counting

const countByProperty = (arr, property, value) => {
    return arr.filter(item => item[property] === value).length;
};

const stopCount = countByProperty(routes, 'return', 0);
const nonStopCount = countByProperty(routes, 'return', 1);

console.log(`1 Stop flights: ${stopCount}`);
console.log(`Non-stop flights: ${nonStopCount}`);
1 Stop flights: 2
Non-stop flights: 1

Comparison

Method Performance Flexibility Readability
forEach + Object O(n) High Good
reduce O(n) High Excellent
filter O(n×m) Medium Excellent

Conclusion

Use reduce for the most elegant solution when counting object properties. The forEach approach offers more control for complex logic, while filter works well for simple, specific counts.

Updated on: 2026-03-15T23:19:00+05:30

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements