0

I want to filter the following array by values. The values including '-usd' need to be replaced without '-usd'. After that I want to only output that replaced values! and not horse or mouse. How can I do this?

So the filtered array may look like:

arr = [
          {animal: 'cat', price: 150},
          {animal: 'dog', price: 350},
        ]

So far i made this:

arr = [
      {animal: 'cat-usd', price: 150},
      {animal: 'dog-usd', price: 350},
      {animal: 'horse', price: 5000},
      {animal: 'mouse', price: 50}
    ]


    var filter = arr.map((i, k) => {
      var ret = i.animal.replace(/-USD/gi, '')
      return ret;
    })

    console.log(filter)

JSBIN

2 Answers 2

3

you can first filter the ones which have -usd in them and then use your map function

var filter = arr.filter(i => i.animal.indexOf('-usd') >= 0).map((i, k) => {
      var ret = i.animal.replace(/-USD/gi, '')
      return ret;
    })
Sign up to request clarification or add additional context in comments.

1 Comment

replace that with .indexOf('-usd') >= 0
1

Check for i.animal.indexOf('-usd') !== -1 in your filter method.

arr = [
  {animal: 'cat-usd', price: 150},
  {animal: 'dog-usd', price: 350},
  {animal: 'horse', price: 5000},
  {animal: 'mouse', price: 50}
];

var filter = arr.filter((i, k) => {
  if(i.animal.indexOf('-usd') !== -1){
    i.animal = i.animal.replace(/-USD/gi, '');
    return i;
  }
})

console.log(filter)

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.