0

I need to filter an array of objects where specific property matches what user has type.

given this

peopleList = [ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "jim foo", age:101},
  {name: "bob wow", age:67},
  {name: "last john", age:43},
]

As soon as the user types the first character I would like to filter the array based not on exact match but on what "where like".

I've check this question: Filtering array of objects with lodash based on property value

but it returns only one exact match or nothing.

What lodash function can I use to return an array of objects where name property matched the query string entered by the user so that if user types 'Jo' this is returned:

[ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "last john", age:43},
]

I am using Angular if that matters.

niko craft
  • 2,893
  • 5
  • 38
  • 67

3 Answers3

2

try this

const peopleList = [ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "jim foo", age:101},
  {name: "bob wow", age:67},
  {name: "last john", age:43},
]
const search = "jo"

cosnt subList = peopleList.filter((person)=>person.name.indexOf(search) > -1)
Ricardo
  • 2,427
  • 19
  • 35
2

In es6 syntax it look like

const filteredArray = peopleList.filter( people => people.name.includes(someText) );
Mixalloff
  • 827
  • 4
  • 10
2

Here is the working snippet without lodash and plain javascript :

var peopleList = [ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "jim foo", age:101},
  {name: "bob wow", age:67},
  {name: "last john", age:43},
];

var result = peopleList.filter(person => person.name.includes("jo"));

console.log(result);
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • can I use this inside .ts files? The large project I am working on is based on typescript, not my decision. If above cant be used what is alternative? – niko craft Mar 28 '18 at 13:20
  • 1
    Yes why not , you can use that without any doubts @nikocraft – Vivek Doshi Mar 28 '18 at 13:21
  • 1
    Can I just add a suggestion, to make this more like an actual `where like` condition, to do the filter on `person.name.toLowerCase()` as `includes()` is case sensitive, although in this specific case, since all the names are lower cased, it wouldn't matter. – Jun Kang Mar 28 '18 at 14:56
  • great suggestion, jun where do I throw in this suggestion considering above code by vivek? – niko craft Mar 28 '18 at 20:24