Home > database >  In nodejs, Find sub array in array
In nodejs, Find sub array in array

Time:09-28


Is there a quickest way to find a sub array in an array ? For exemple with anonymous methods ?
In my case, the master array is a frame of bytes received from a device, the sub-array is the characteristic sequence of the beginning of the waited answer. The device is a Lidar, so the best is the quickest possible processing.
function findSubArray( master, sub, fromPos) {
    let pos = null;
    if ( ! fromPos) fromPos = 0;
    
    do {
        if (master.length < sub.length) break;
        if (fromPos > (master.length - sub.length)) break;
        
        for( m=fromPos; m < (master.length - sub.length); m  ) {
            
            let masterPos = m;
            for( s=0; s < sub.length; s  ) {
                if (sub[s] != master[m   s]) {
                    masterPos = -1;
                    break;
                }
            }
            if (masterPos != -1) {
                pos = masterPos;
                break;
            }
        }
    } while( false);
    return pos;
}

Best regards.

CodePudding user response:

You could look at geeksforgeeks for those type of problems.

I found this O(N) solution that could be applied for your problem.

https://www.geeksforgeeks.org/check-whether-an-array-is-subarray-of-another-array/

just store the first index when starting a new sub-sequence and you have the position.

CodePudding user response:

You can do:

const master = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const sub = [4, 5, 6]

const findSubArray = (master, sub) => master.find(a => JSON.stringify(a) === JSON.stringify(sub))

console.log(findSubArray(master, sub))

  • Related