如何获取匹配特定字符串的JSON对象数组长度及排除pending的friends数组长度?
Hey there! Let's tackle your two questions one by one:
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.
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

