1

I am trying to filter an array, but am having issues with returning only the values which are true (status: yes).

 var arr = {
     "status": "Yes"
  },
  {
      "status": "No"
  },
  {
      "status": "No"
  },
  {
      "status": "No"
  }


  var filteredResult = [];

  for (var i = 0; i < arr.length; i++) {
  if(arr[i].status == "Yes") {
    filteredResult.push(status);
  }
}

console.log (filteredResult);

I am still learning JS, but I hope to improve. Thank you.

2
  • 1
    status should be arr[i]. Commented Jun 9, 2021 at 23:31
  • There is a function exactly for this purpose. Commented Jun 9, 2021 at 23:34

2 Answers 2

1

I don't think this code compiles - you need to include square brackets to declare an array.

const arr = 
  [{ "status": "Yes" },
  { "status": "No" },
  { "status": "No" },
  { "status": "No" }]

Then to filter it, just do

const results = arr.filter((item) => { return item.status === "Yes" })
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This is great, and an arrow function too. Which I have only just started learning about.
or more short : arr.filter( i => i.status === "Yes" )
0

Your syntax is wrong so for loop won't work. The array should be inside "[]". Refer to the below code. I have tested and is working fine.

If you want to get list of all object having status "Yes", then use filteredResult.push(arr[i]), else filteredResult.push(arr[i].status) if you need strings of "Yes"

var arr = [{
     "status": "Yes"
  },
  {
      "status": "No"
  },
  {
      "status": "No"
  },
  {
      "status": "No"
  }]


  var filteredResult = [];

  for (var i = 0; i < arr.length; i++) {
      if(arr[i].status == "Yes") {
        filteredResult.push(arr[i]);
      }
  }

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.