JSFiddle - React, Tailwind, and code Playground

by Pankaj Kargirwar

JavaScript

function findBeamPairs(notes) {
    const beamStarts = []; // Array to store notes where a beam starts
    const beamPairs = []; // Array to store pairs of notes where a beam starts and ends

    // Iterate through the array of notes
    notes.forEach(note => {
        // If the current note has a beam
        if (note.hasBeam) {
            // Add it to the array of beam starts
            beamStarts.push(note);
        } else {
            // If the current note doesn't have a beam,
            // it may be the end of a beam
            // Check if there are any beam starts before it
            if (beamStarts.length > 0) {
                // Get the last beam start note
                const beamStartNote = beamStarts.pop();

                // Add the pair to the array of beam pairs
                beamPairs.push({ start: beamStartNote, end: note });
            }
        }
    });

    return beamPairs;
}

// Example usage:
const notes = [
    { pitch: 'C', hasBeam: true, beamId: 1 },
    { pitch: 'D', hasBeam: true, beamId: 1 },
    { pitch: 'E', hasBeam: false },
    { pitch: 'F', hasBeam: false },
    { pitch: 'G', hasBeam: true, beamId: 2 },
    { pitch: 'A', hasBeam: false },
    { pitch: 'B', hasBeam: true, beamId: 2 },
];

const beamPairs = findBeamPairs(notes);
console.log(beamPairs);