How to detect duplicate values in JavaScript JSON array and return boolean

I have a JSON structure with nested arrays and I’m trying to identify duplicates based on a certain field. Here’s the data I’m working with:

"Records": [
    ["date": "2023-03-15", "activity": "Workshop"],
    ["date": "2023-03-15", "activity": "Workshop"], 
    ["date": "2023-03-16", "activity": "Workshop"]
]

I want to know if the "2023-03-15" date appears more than once in this array. If it does, I’m looking for the function to return true. What’s the most effective way to iterate through this data and count how many times a specific date value appears? I’ve attempted various methods but haven’t succeeded in establishing the logic for finding duplicates.

you can also use filter to check for duplicates. just do records.filter(r => r.date === '2023-03-15').length > 1 and it’ll return true/false for that specific date.

Try using a frequency counter with a regular loop instead. This works great with larger datasets since it bails out the moment it hits a duplicate instead of churning through everything:

function hasDuplicateDates(records) {
    const dateCount = {};
    for (let record of records) {
        if (dateCount[record.date]) {
            return true;
        }
        dateCount[record.date] = 1;
    }
    return false;
}

It’s way more memory efficient when you’ve got tons of unique dates but just need to catch duplicates. Exits right when it finds the first match rather than building out complete arrays or sets.

You can catch duplicate dates in your JSON array using map and a Set. This approach involves creating an array of dates from your records and converting that array into a Set, which inherently removes duplicates. By comparing the lengths of the original array and the Set, it’s easy to determine if duplicates exist. Here’s the function you can use:

function hasDuplicateDates(records) {
    const dates = records.map(record => record.date);
    return dates.length !== new Set(dates).size;
}

Alternatively, you can use some() in conjunction with indexOf() and lastIndexOf(). This method checks whether any date appears more than once:

function hasDuplicateDates(records) {
    const dates = records.map(record => record.date);
    return dates.some((date, index) => dates.indexOf(date) !== dates.lastIndexOf(date));
}

Both functions will return true when duplicates appear in your array.