-1

I want to get all the values that equal a certain number and count how many of each of the objects.

My code looks like this:

var countItems = {
    "aa":"70",
    "bb":"70",
    "cc":"80",
    "dd":"90",
    "ee":"90",
    "ff":"90"
}

Now what I want to do is count each on that is in the second half.

For example, there are two "70", one "80", and three 90. Then I can assign to variables:

var firstCounter  = ?? // 2
var secondCounter = ?? // 1
var thirdCounter  = ?? // 3

?? is I don't know what goes here.

If it was structed differently like the following, I could do it like this:

let firstCounter = 0;
for (let i = 0; i < countItems.length; i++) {
  if (countItems[i].status === '70') firstCounter++;
}

let secondCounter = 0;
for (let i = 0; i < countItems.length; i++) {
  if (countItems[i].status === '80') secondCounter++;
}

let thirdCounter = 0;
for (let i = 0; i < countItems.length; i++) {
  if (countItems[i].status === '90') thirdCounter++;
}

But the thing is, my original code which is what I have is not structured like that, so I'm not sure how to adapt it.

How can I count the items in the original list (var countItems) so that I can find out how much each value is?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
sdsdc1
  • 13
  • 5

6 Answers6

1

You could use Object.values(countItems) to get an array that looks like this: ["70","70","80","90","90","90"] then either use a for loop to conditionally increment whatever counters you want, or use something like Array.reduce or Array.filter to count the elements you need.

ahrampy
  • 173
  • 2
  • 2
  • 9
0

You could use reduce to create a counted hash map like so:

const countItems = [
  { data: 'aa', status: '70' },
  { data: 'bb', status: '70' },
  { data: 'cc', status: '80' },
  { data: 'dd', status: '90' },
  { data: 'ee', status: '90' },
  { data: 'ff', status: '90' },
];

const countedHash = countItems.reduce((acc, curr) => {
  if (!acc[curr.status])
    acc[curr.status] = 1
  else
    acc[curr.status] += 1
  return acc
}, {})

/* print out the results */
console.log(countedHash)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Asleepace
  • 3,466
  • 2
  • 23
  • 36
  • The array you posted an answer to was only an example but it wasn't the code I'm trying to extract from – sdsdc1 May 24 '22 at 23:31
  • @sdsdc1 no worries this will count objects in an array, the only thing you may need to change is the `status` property – Asleepace May 24 '22 at 23:32
0

You can access object keys like this :

countItems["aa"] // it will return "70"

You can also loop on the object (if you want to do as you did in your example) :

for (const item in countItems) {
    console.log(countItems[item])
    if (countItems[item] == "70") firstCounter++;
    
}
Pwoo
  • 19
  • 5
0

Object.values() and reduce() are both the right ideas. Taken together...

var countItems = {
    "aa":"70",
    "bb":"70",
    "cc":"80",
    "dd":"90",
    "ee":"90",
    "ff":"90"
};

let counts = Object.values(countItems).reduce((acc, value) => {
  if (!acc[value]) acc[value] = 0;
  acc[value]++;
  return acc;
}, {});

let [theFirstValue, theSecondValue, theThirdValue] = Object.values(counts)

console.log(theFirstValue, theSecondValue, theThirdValue);
danh
  • 62,181
  • 10
  • 95
  • 136
0
const countItems = [
  { data: 'aa', status: '70' },
  { data: 'bb', status: '70' },
  { data: 'cc', status: '80' },
  { data: 'dd', status: '90' },
  { data: 'ee', status: '90' },
  { data: 'ff', status: '90' },
]; 

var countValues = Object.values(countItems);
let obj ={}
for(let val of countValues){
  if(!obj[val.status]){
    obj[val.status] = 1
  }else{
    obj[val.status] += 1
  }
}
 console.log(obj)
Matyas92
  • 1
  • 2
  • You answered the wrong problem. I know how to solve this one, I didn't know how to solve the original one. I only gave this as an example. This doesn't solve the problem I asked. – sdsdc1 May 24 '22 at 23:59
0

const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];

const countedNames = names.reduce((allNames, name) => {
  const currCount = allNames[name] ?? 0;
  return {
    ...allNames,
    [name]: currCount + 1,
  };
}, {});


// results in countedNames having a value of:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

The reduce() method on the names array to count the occurrences of each name and store the results in the countedNames object. Let's go through the code step by step to understand how it works:

const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"]; Here, we initialize an array called names containing several names, including duplicate entries.

const countedNames = names.reduce((allNames, name) => {...}, {}); We declare a variable countedNames and assign it the result of the reduce() method applied to the names array. The reduce() method iterates over each element of the array and accumulates a single value based on a callback function.

(allNames, name) => {...} This is the callback function provided to the reduce() method. It takes two parameters: allNames and name. allNames represents the accumulated object that will hold the counts of each name, and name represents the current element being processed.

const currCount = allNames[name] ?? 0; Inside the callback function, we retrieve the current count for the name from the allNames object. If the name doesn't exist in the allNames object, currCount is set to 0.

return {...allNames, [name]: currCount + 1}; We return a new object that combines the existing allNames object with a new property [name] whose value is currCount + 1. This increments the count of the current name by 1.

{} (initial value for reduce()) The {} passed as the second argument to reduce() is the initial value for the allNames parameter. It represents an empty object that will store the counts of each name.

The reduce() method iterates over each name in the names array, and for each name, it checks if it already exists in the allNames object. If it exists, it increments the count by 1; otherwise, it adds the name as a new property with a count of 1. This process accumulates the counts of each name, resulting in the final countedNames object:

{ 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
user3784130
  • 71
  • 1
  • 2