Search code examples
javascriptlodash

Is there a simpler lodash technique to search array parameter?


I'm only looking for lodash based solution. I cannot use javascript 6 features.

The below code works. It finds the "record" that contains the requested string in the circleStoreId array. I feel like there should be a simpler, more lo-dashy way to achieve this. Am I missing a better solution?

var RECORDS = [
    {
        circleStoreId: [
            'AKWX3MWZ0FFT6',    //  WS Herb Counter
            'C9VKT4W6GQNBM',    //  WS Bar
            'KPN3W7SHAH1P6'     //  WS Front Counter
            ],
        acmeLocationIId: 3,
        channelIId: 2
    },
    {
        circleStoreId: [
            '0ZK8FZHPD5G71',    //  SK Herb Counter
            '6VCZ7NNAF2VWW'     //  SK Bar
            ],
        acmeLocationIId: 4,
        channelIId: 1
    }
    //  Ready for the next retail location to be added...
];

var f = _.find(RECORDS, function(r) {
    return _.indexOf(r.circleStoreId, '6VCZ7NNAF2VWW') > -1;
});

console.log(f)

The console will output

{circleStoreId: Array(2), acmeLocationIId: 4, channelIId: 1}


Solution

  • Maybe using includes instead of indexOf. But it does not improve that much.

    var f = _.find(RECORDS, function(r) {
        return _.includes(r.circleStoreId, '6VCZ7NNAF2VWW'));
    });
    
    console.log(f)