1

I have the following array:

PeopleList

[ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"},
  {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"},
 {id:5, name:"Peter", status:"inactive"}
]

statusList

[ 'active', 'pending']

I want to filter the object array to only the statusList so I did the following:

var filteredPeople  =PeopleList.map(person => {
  for (var i=0; i<=statusList.length; i++){
    if(statusList[i] == person.active)
        return {...person};
  }
});

While the person objects return correctly, I also get "undefined" for objects that didn't pass the conditional statement.

So my result is:

   [object, object, object,object, undefined ] 

How can I make it so that if the conditional does not pass, I remove that object from the list?

2 Answers 2

1

Instead of map you should use filter for filtering array. You can also use includes.

var data = [ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"},
  {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"},
 {id:5, name:"Peter", status:"inactive"}
]
var statusList = [ 'active', 'pending']

var result = data.filter(e => statusList.includes(e.status))
console.log(result)

With ES5 and older versions you can use indexOf instead of includes.

var data = [ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"},
  {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"},
 {id:5, name:"Peter", status:"inactive"}
]
var statusList = [ 'active', 'pending']

var result = data.filter(function(e) {
  return statusList.indexOf(e.status) != -1
})
console.log(result)

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

Comments

0
var statusList = [];

var PeopleList = [

  { id: 1, name: "Brian", status: "active" },
  { id: 2, name: "Mary", status: "active" },
  { id: 3, name: "John", status: "pending" },
  { id: 4, name: "Steph", status: "pending" },
  { id: 5, name: "Peter", status: "inactive" }

];

for (var counter = 0; counter < PeopleList.length; counter++)
{

statusList.push(PeopleList[counter].status);

document.write(PeopleList[counter].status + "<br />");
}

// Here is your Status array
console.log(statusList);

// loop through all elements in your javascript status array and print them out
for (var i = 0; i < statusList.length; i++)
{

    document.write("<strong>" + statusList[i] + "<br />");
}

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.