2

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.

3 Answers 3

5

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

0

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)})));

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.