1

How Do I filter an array by checking if an array is listed in the array?

cryptoData: Array(100) 0: {CoinInfo: {…}, RAW: {…}, DISPLAY: {…}}

I am trying to check if cryptoData (Array) contains the DISPLAY array and if it does not contain DISPLAY - remove it from the cryptoData array and set the filterArray with only the elements that contain the DISPLAY Array.

My attempt:

var filterdArray = cryptoData.filter(function (el) {
  return cryptoData[el] === 'DISPLAY';
});

this.setState({
  cryptos: filterdArray,
  refreshing: false,
});
2
  • el is the element, not the array index. Why do you have cryptoData[el]? Commented Nov 16, 2021 at 17:08
  • 2
    Please be sure to format code correctly. Commented Nov 16, 2021 at 17:11

1 Answer 1

2

As the value is an object you can use hasOwnProperty to check if the object has a property.

var filterdArray = cryptoData.filter(function (el) {
  return el.hasOwnProperty('DISPLAY');
});

this.setState({
  cryptos: filterdArray,
  refreshing: false,
});
Sign up to request clarification or add additional context in comments.

2 Comments

what is the difference between the first parameter and second in the filter callback function?
the first one is the element and the second one is the index at which the element is located.

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.