0

I am trying to filter my array in my angular 4 component. The array has a property which itself is an array too:

export const data = [
  {
    "number": "1",
    "lines": [
      "aaaaabbbb bbbbb ccccc ddddd",
      "aaaaabbbb bbbbb ccccc ddddd",
      "aaaaabbbb bbbbb ccccc ddddd",

    ]
  }
  ,
  {
    "number": "2",
    "lines": [
      "aaaaabbbb bbbbb ccccc ddddd",
      "aaaaabbbb bbbbb ccccc ddddd",
      "aaaaabbbb bbbbb ccccc ddddd",

    ]
  }
  ,
  {
    "number": "3",
    "lines": [
      "aaaaabbbb bbbbb ccccc ddddd",
      "aaaaabbbb bbbbb ccccc ddddd",
      "aaaaabbbb bbbbb ccccc ddddd",
    ]
  }
  ]

This is part of the component.html:

<input (keyup)="search($event.target.value)" />
<tr *ngFor="let item of filteredData">
        <td>{{item.number}}</td>
        <td>{{item.lines}}</td>
</tr>

This is part of the filter/search ts-code:

export class AppComponent {
    filteredData = data;

    search(val: any) {
            let ind = false;
            console.log(val);
            if (!val) this.filteredData = this.data;
            //this statement does not work:
            this.filteredData = this.data.filter(item=> item.lines.indexOf(val) >=0)
    }
}

How can I filter my data? Ignore the angularcode it is more about the filter statement.

2
  • What's wrong with your current code? Commented Dec 3, 2017 at 1:59
  • I updated the question. When I search for 'bbbbb' for example it does not return anything. Commented Dec 3, 2017 at 2:03

2 Answers 2

1

Something like this

this.filteredData = this.data.filter((item) => {
  return item.lines.filter((inner) => {
    return inner.includes(val);
  }).length > 0;
});

Or

for (const item of this.data) {
  for (const inner of item.lines) {
    if (inner.includes(val)) {
      return item;
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Filtering based on item.lines.indexOf(val) is effectively saying:

Give me only the items where at least one of the objects in item.lines is equal to val.

This is not the same as what you're trying to do, which is:

Give me only the items where at least one of the objects in item.lines contains val as a substring.

You need to iterate over item.lines as well to get the intended result - something alone these lines* should work:

item => item.lines.includes(line => line.indexOf(val) >= 0)

Issues like this where you're accidentally calling a method on the array rather than its contents are usually easy to spot, since you'd get an error - this one was complicated by the fact that both Array and String have a method called indexOf!

* pun not intended

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.