0

I want to filter data based on a selection value of select box.

<select id="testDD">
    <option value="local">Local</option>
    <option value="international">Internationl</option>
</select>
<div id="list"><!-- List Items to be generated from #testDD value --></div>

I have data object like this

var data = [
    {type: 'local', name: 'abc1', location: 'xyz1'},
    {type: 'local', name: 'abc2', location: 'xyz2'},
    {type: 'international', name: 'abc3', location: 'xyz3'},
    {type: 'local', name: 'abc4', location: 'xyz4'},
    {type: 'local', name: 'abc5', location: 'xyz5'},
    {type: 'international', name: 'abc6', location: 'xyz6'},
    {type: 'international', name: 'abc7', location: 'xyz7'}
]

Whats the ideal way to filter out data based on selection event changed?

Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
coure2011
  • 40,286
  • 83
  • 216
  • 349

2 Answers2

0

const data = [
    {type: 'local', name: 'abc1', location: 'xyz1'},
    {type: 'local', name: 'abc2', location: 'xyz2'},
    {type: 'international', name: 'abc3', location: 'xyz3'},
    {type: 'local', name: 'abc4', location: 'xyz4'},
    {type: 'local', name: 'abc5', location: 'xyz5'},
    {type: 'international', name: 'abc6', location: 'xyz6'},
    {type: 'international', name: 'abc7', location: 'xyz7'}
];

const filterStream = Rx.Observable.fromEvent(document.getElementById('testDD'), 'change');


filterStream
  .map(evt => evt.target.value)
  .startWith(null)
  .subscribe(filterTypeName => {
    const filteredData = data.filter(d => d.type === filterTypeName || !filterTypeName);
    document.getElementById('list').innerText = JSON.stringify(filteredData);
  });
<script src="https://unpkg.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
  <select id="testDD">
    <option value="">Select to filter</option>
    <option value="local">Local</option>
    <option value="international">Internationl</option>
  </select>
  
  <h2>filtered resuls</h2>
  <div id="list">
    <!-- List Items to be generated from #testDD value -->
  </div>
Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
-1

Using Subjects and Observables might be a cleaner approach. This answer uses a Subject to store the value, an Observable to watch it for changes, and a function to change the value of the Subject.

Homer
  • 7,594
  • 14
  • 69
  • 109