Leonel Matias Domingos
Leonel Matias Domingos

Reputation: 2070

filter array with lodash

I have an array and i need to filter it. What happen is that if i use

var results = _.filter(arr, function (ob) {
                        return ob.VAL.indexOf(search) !== -1;
                    });

all the objects are returned cause they contain '0@1900-01-01' .I just want the first one to be returned

search='0@1900'
arr=[
{
    "DSR_MOTIVO": "Falta de nada",
    "VAL": "0@1900-01-01@111@1900-01-01"
  },
  {
    "DSR_MOTIVO": "Falta de Plano",
    "VAL": "100@1900-01-01@111@1900-01-01"
  },
  {
    "DSR_MOTIVO": "Fabrica Encerrada",
    "VAL": "100@1900-01-01@150@1900-01-01"
  },
  {
    "DSR_MOTIVO": "Refeicoes",
    "VAL": "200@1900-01-01@212@1900-01-01"
  },
  {
    "DSR_MOTIVO": "Lanche/WC",
    "VAL": "200@1900-01-01@213@1900-01-01"
  }  
]

Maybe a regular expression.

Upvotes: 0

Views: 148

Answers (2)

Leonel Matias Domingos
Leonel Matias Domingos

Reputation: 2070

Solved with _.startsWith

var results = _.filter(arr, function (ob) {
                                    if(_.startsWith(ob.VAL, search)`enter code here`){
                                        return ob.VAL;
                                    }
                                });

Upvotes: 0

Andrew D
Andrew D

Reputation: 207

If you just want the first match, the _.find function should do the job: https://lodash.com/docs/4.16.4#find

Upvotes: 2

Related Questions