You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取匹配特定字符串的JSON对象数组长度及排除pending的friends数组长度?

Hey there! Let's tackle your two questions one by one:

1. 获取匹配特定字符串的JSON对象数组的长度

The simplest way to get the count of objects that match a specific string is to use the filter() method to narrow down the array to only matching items, then grab the length property of the resulting array.

For example, say you have an array of user objects and you want to count how many have the name "Alice":

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Alice" },
  { id: 4, name: "Charlie" }
];

// Match exact string
const matchingCount = users.filter(user => user.name === "Alice").length;
console.log(matchingCount); // Output: 2

If you need to match strings that contain a specific substring (instead of exact matches), swap the strict equality check with includes():

// Match substring
const partialMatchCount = users.filter(user => user.name.includes("Ali")).length;
console.log(partialMatchCount); // Output: 2

filter() creates a new array with all elements that pass your test, so accessing its length gives you the exact number of matching objects.

2. 排除pending项后的数组长度:更简便的实现方式

Your initial thought of using filter() + length works perfectly and is super readable:

const friends = [
  { id: 1, status: "active" },
  { id: 2, status: "pending" },
  { id: 3, status: "active" },
  { id: 4, status: "blocked" }
];

// Basic approach
const nonPendingCount = friends.filter(friend => friend.status !== "pending").length;
console.log(nonPendingCount); // Output: 3

But if you want a more memory-efficient approach (especially for large arrays), use reduce() instead. Unlike filter(), which creates a new array, reduce() just counts the valid items directly without extra array overhead:

// More efficient counting with reduce
const nonPendingCount = friends.reduce((total, friend) => {
  return friend.status !== "pending" ? total + 1 : total;
}, 0);
console.log(nonPendingCount); // Output: 3

For small arrays, the performance difference is negligible, but reduce() shines when you're dealing with hundreds/thousands of items since it avoids creating an intermediate array. It's also a clean way to handle counting logic in one step!

内容的提问来源于stack exchange,提问作者totalnoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:12:20