Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

reduce tally

const pets = ["dog", "chicken", "cat", "dog", "chicken", "chicken", "rabbit"];

const petCounts = pets.reduce(function(obj, pet) {
  if (!obj[pet]) {
    // if the pet doesn't yet exist as a property of the accumulator object,
    //   add it as a property and set its count to 1
    obj[pet] = 1;
  } else {
    // pet exists, so increment its count
    obj[pet]++;
  }
  
  return obj; // return the modified object to be used as accumulator in the next iteration
}, {}); // initialize the accumulator as an empty object

console.log(petCounts);
/*
{
  dog: 2, 
  chicken: 3, 
  cat: 1, 
  rabbit: 1 
}
*/
Comment

PREVIOUS NEXT
Code Example
Javascript :: kitten ui input height multiline 
Javascript :: escape exponential input number in js 
Javascript :: js array take a elemt to front 
Javascript :: close element on click outside 
Javascript :: alert(document.cookie); 
Javascript :: function for making something invisible in gdscript 
Javascript :: clone copy a table in servicenow 
Javascript :: compile regex script help online 
Javascript :: java script loup object 
Javascript :: how to send email 
Javascript :: javascript filtrar array string 
Javascript :: react native asyncstorage mergeItem example 
Javascript :: Component on new window 
Javascript :: Make an array from the HTML Collection to make it iterable 
Javascript :: array of function 
Javascript :: 4.6.3. Order of Operations¶ 
Javascript :: react-pdf responsive 
Javascript :: basic routes 
Javascript :: joi for validation 
Javascript :: custom validator Whitelisting 
Javascript :: react redux reducer add objects to reducer 
Javascript :: Quitar objetos duplicados 
Javascript :: Example of Nullish coalescing assignment operator in es12 
Javascript :: how add element at beginning of array in javascript using splice 
Javascript :: stimulus controller 
Javascript :: mm2javascript 
Javascript :: react break out of useeffect 
Javascript :: jsx tag with children react js 
Javascript :: node app not visible in browser aws ec2 
Javascript :: react avoid spreading non-dom props across component 
ADD CONTENT
Topic
Content
Source link
Name
5+2 =