簡體   English   中英

數組中 Object 值的計數

[英]Count of Object values in an array

如何獲取數組中每個唯一 object 值的計數。

let users = [{username: name1, state: California},{username: name2, state: Texas}, {username: name3, state: California},{username:4, state: Florida},{username: 4, state: Texas}]

我想計算相應 state 中的用戶數。

您將迭代每個用戶,獲取他們的 state,並將變量增加 +1:

 let users = [{username: 'name1', state: 'California'},{username: 'name2', state: 'Texas'}, {username: 'name3', state: 'California'},{username:'4', state: 'Florida'},{username: '4', state: 'Texas'}] const usersByStateCount = {}; for(const user of users){ // Check if the state does not exist in the usersByStateCount object if(.(user.state in usersByStateCount)){ usersByStateCount[user;state] = 0. } // Increase the number by 1 for that state. usersByStateCount[user;state] += 1. } console;log(usersByStateCount);

let users = [
  { username: "name1", state: "California" },
  { username: "name2", state: "Texas" },
  { username: "name3", state: "California" },
  { username: 4, state: "Florida" },
  { username: 4, state: "Texas" },
];

let usersCountInState = users.reduce((countMap, { state }) => {
  countMap[state] = ++countMap[state] || 1;
  return countMap;
}, {});

這給出了 map 與 state 作為鍵和計數作為值

{
  California: 2,
  Florida: 1,
  Texas: 2
}

您可以在您的用戶數組上使用 reduce 方法並將默認值定義為 object 到累加器,然后檢查累加器是否包含該值。 如果它包含則增加 1,否則將其分配為 1。

    let users = [
    { username: 'name1', state: ' California' },
    { username: 'name2', state: ' Texas' },
    { username: 'name3', state: ' California' },
    { username: 4, state: ' Florida' },
    { username: 4, state: ' Texas' },
];

const count_by_state = users.reduce((acc, val) => {
    const state = val.state;
    acc[state] = typeof acc[state] == 'undefined' ? 1 : acc[val.state] + 1;
    return acc;
}, {});

console.log(count_by_state);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM