meallhour
meallhour

Reputation: 15591

How to capture matching count value in an array?

I have an array x which can have following values:

0: {status: "completed", count: 2}
1: {status: "pending", count: 3}

Now, if status is matching to pending then I want to capture the corresponding the count value.

I have written the following code:

if (x?.length) {
PendingCount = x[1].count;
completedCount = x[0].count;
}

This is not always giving the desired output because it is not necessary that pending status will always be at the x[0]

Upvotes: 1

Views: 353

Answers (4)

Tom O.
Tom O.

Reputation: 5951

If it's guaranteed that there will only be 1 element with "pending" status, then it seems appropriate to use Array.prototype.find to find the element based on the value of its status property:

const pendingCount = [{
  status: "completed",
  count: 2
}, {
  status: "pending",
  count: 3
}].find(el => el.status === "pending").count;

console.dir(`pending count = ${pendingCount}`);

If there are multiple "pending" items in the array and you need to get the sum of all, it would probably make most sense to use Array.prototype.filter (to remove all non "pending" items) and then Array.prototype.reduce on the filter result to add the counts.

const pendingSum = [{
    status: "completed",
    count: 2
  }, {
    status: "pending",
    count: 3
  }, {
    status: "pending",
    count: 5
  }, {
    status: "pending",
    count: 5
  }]
  .filter(el => el.status === "pending")
  .reduce((sum, el) => sum += el.count, 0);

console.dir(`sum of pending items count = ${pendingSum}`);

Upvotes: 2

jonowles
jonowles

Reputation: 466

I would use Array.prototype.find to find the item with pending status and then take its count property, like so:

const { count } = x.find(({ status } = {}) => status === 'pending') || {}:

That will give you the count if a pending status exists, or undefined if one does not. I've used destructuring and defaulting syntax here, take a look at the articles I've linked if you're unfamiliar with them.

Upvotes: 2

Nonik
Nonik

Reputation: 655

you can use filter, will find all elements that have pending status

const data = [{
    status: "completed",
    count: 2
  },
  {
    status: "pending",
    count: 3
  }
];

const pending = data.filter(s => s.status === "pending");
console.log(pending.length ? "got pending" : "no pending")
console.log(pending.map(i=>i.count))

Upvotes: 2

Or Assayag
Or Assayag

Reputation: 6336

const array = [
  {status: "completed", count: 2},
  {status: "pending", count: 3}
];

const pending = array.find(s => s.status === "pending");
if (pending) {
   // Do whatever you want.
}

Upvotes: 1

Related Questions