tleveque
tleveque

Reputation: 547

How to filter array inside another array

Let say I have a array like this:

[
  {
    name:"1",
    args: [1,2,3,4,5]
  },
  {
    name:"2",
    args: [2,3,4,5,6]
  }
]

What I want to do, is to remove all "args" that have a value < 4, to have the following result:

[
  {
    name:"1",
    args: [4,5]
  },
  {
    name:"2",
    args: [4,5,6]
  }
]

How can I do that using Observables (Rxjs). I tried with mergeMap, but it does seems to do what I want.

Upvotes: 2

Views: 4925

Answers (3)

vanelizarov
vanelizarov

Reputation: 1073

If you want RxJS-way solution, it might look something like this:

ES6 syntax:

const arr = [
  {
    name:"1",
    args: [1,2,3,4,5]
  },
  {
    name:"2",
    args: [2,3,4,5,6]
  }
]

Rx.Observable
  .from(arr) // 1
  .map(item => { // 2
    return {
      ...item,
      args: item.args.filter(arg => arg >= 4) // 3
    }
  })
  .reduce((acc, value) => [...acc, value], []) // 4
  .subscribe(result => {
    console.log(result) // 5
  })

ES5 syntax:

var arr = [
  {
    name:"1",
    args: [1,2,3,4,5]
  },
  {
    name:"2",
    args: [2,3,4,5,6]
  }
]

Rx.Observable
  .from(arr)
  .map(function(item) {
    return {
        name: item.name,
        args: item.args.filter(function(arg) {
        return arg >= 4
      })
    }
  })
  .reduce(function(acc, value) {
    return [].concat(acc, value)
  }, [])
  .subscribe(function(result) {
    console.log(result)
  })
  1. Create Observable sequence from array
  2. Modify each streamed item in array corresponding to your needs
  3. Actual args filtering
  4. Reduce all streamed results into one array (you can remove this line if you want then process each item of array one-by-one, not the whole array)
  5. Do something with result

Some useful links:

Upvotes: 1

void
void

Reputation: 36703

You can do this pretty easily using plain JS.

var data = [
  {
    name:"1",
    args: [1,2,3,4,5]
  },
  {
    name:"2",
    args: [2,3,4,5,6]
  }
];

var parsedData = data.map(function(el){
    el.args = el.args.filter(function(x){ return x >= 4; });
    return el;
});

console.log(parsedData);

Upvotes: 5

bryan60
bryan60

Reputation: 29335

observables are for manipulations of streams of data over time, so they are array like but they are not arrays. If this data is coming through an observable, you should just use map and then use normal array operators inside the observable map, because you're just manipulating a single data point in the stream:

source.map(data => data.map(d => Object.assign(d, {args:d.args.filter(v => v >= 4)})));

Upvotes: 0

Related Questions