0

I have an array like this:

user:[
  { name: "A", mobile: "123", status: "active"},
  { name: "B", mobile: "123", status: "active"},
  { name: "C", mobile: "123", status: "active"},
  { name: "D", mobile: "123", status: "active"},
  { name: "E", mobile: "123", status: "inactive"},
  { name: "F", mobile: "123", status: "inactive"},
];

Right now my code displays 4 records with "active" users first and "inactive" users at last

user.sort((a, b) =>a.status_id.localeCompare(b.status_id)).slice(0,4).map((d))

OUTPUT:

active
active
active
active

But what I want to display is - first half should be "active" and second half should be "inactive" and if there is no "inactive" user, then all should display "active" users

Displaying 4 records
active
active
inactive
inactive

How can I do this?

4
  • you are expecting to display 6 records finally? Commented Aug 2, 2021 at 5:22
  • @AmruthLS No,only 4 records Commented Aug 2, 2021 at 5:24
  • whats your logic to display 4 records ? 2 from active 2 from inactive ? Commented Aug 2, 2021 at 5:25
  • @AmruthLS Yes, 2 from active and 2 from inactive Commented Aug 2, 2021 at 5:27

1 Answer 1

1

This should help you

let user = [
  { name: "A", mobile: "123", status: "active"},
  { name: "B", mobile: "123", status: "active"},
  { name: "C", mobile: "123", status: "active"},
  { name: "D", mobile: "123", status: "active"},
  { name: "E", mobile: "123", status: "inactive"},
  { name: "F", mobile: "123", status: "inactive"},
];

let active = user.sort((a, b) =>a.status.localeCompare(b.status)).slice(0,2);
let inactive = user.sort((a, b) =>b.status.localeCompare(a.status)).slice(0,2);
let final = active.concat(inactive);
console.log(final)

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

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.