JS_basic_knowledge
JS_basic_knowledge

Reputation: 117

Filtering result using Javascript

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.

Upvotes: 1

Views: 426

Answers (2)

katamaster818
katamaster818

Reputation: 341

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

Upvotes: 1

Vivek
Vivek

Reputation: 75

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

Upvotes: 0

Related Questions