How to nicely filter inside an array of object?


#1

Hi,

I read in Ionic doc and on the web that you can easily filter an array by using filter(). Something like

return this.items.filter((v) => {
  if(v.toLowerCase().indexOf(q.toLowerCase()) >= 0) {
    return true;
  }
  return false;
})

But what if the “items” is an array of objects?

What I have done seems to work, but I thought it could be nicer than that:

let newList : IInfo[] = new Array<IInfo>;

for (let idx = 0; idx < this.myList.length; idx++) {    
  if (myList[idx].id.indexOf(str) >= 0) 
    newList.push(this.myList[idx]);
  else if (myList[idx].name.indexOf(str) >= 0)
    newList.push(this.myList[idx]);
  else if (myList[idx].position.indexOf(str) >= 0)
    newList.push(this.myList[idx]);
})

Do you have other better suggestion?


#2

you can simple work with and array of objects in your filter function. (btw this an array-function and has nothing todo with angular --> https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
Then you would something like that:

return this.items.filter((item) => {
  if (item.id.indexOf(str) >= 0) {
    return true;
  }
  if (item.name.indexOf(str) >= 0) {
    return true;
  }
  if (item.position.indexOf(str) >= 0) {
    return true;
  }
  return false;
})

#3

Make sense! Thanks @bengtler


#4

You can actually shorten the code with a bit of logic:

return this.items.filter((item) => {
  if (item.id.indexOf(str) >= 0 ||
      item.name.indexOf(str) >= 0 ||
      item.position.indexOf(str) >= 0) {
    return true
  }
  return false
})

Now it’s 8 lines instead of 12, well actually 6 if you think the if condition as 1 long line.


#5

Also ES6 comes with includes which will replace that ugly indexOf(str) >= 0, supported in the most important browsers like Edge, FF>= 43, Chrome and Opera, and Node >= 4, it would look like:return this.items.filter((item) => {

return this.items.filter((item) => {
  if (item.id.contains(str) ||
      item.name.contains(str) ||
      item.position.contains(str)) {
    return true
  }
  return false
})

#6

includes or contains?

Or even shorter:

return this.items.filter(item => item.id.includes(str) ||
    item.name.includes(str) ||
    item.position.includes(str)
)

#7

Whyyy do i keep forgeting the implicit return of ES6 arrow function? good call there @willb.


#8

Thank you all for your help! I really appreciated all the different suggestions!


#9

Did this change with the R.C. version? I can’t get this to work properly. I tried every possibility.