Jean-Luc-Picard
Jean-Luc-Picard

Reputation: 31

Count JavaScript object value in array for duplicates

Hello I am new to the community and this is my first question.

/// I have an array of objects. Will be a few hundred at some point.

var locations = [{
    "name": "Costco",
    "city": "San Francisco",
    "state": "CA",
    "zip": "75201",
}, {
    "name": "Safeway",
    "city": "Appleton",
    "state": "WI",
    "zip": "90210",
}, {
    "name": "Foodmart",
    "city": "Orlando",
    "state": "FL",
    "zip": "90210",
}, {
    "name": "Trader Joes",
    "city": "Concord",
    "state": "CA",
    "zip": "90210",
}];

/// I need to count each "state:" and hold the value as a variable like below.

var CA
/// Value would be 2

var FL
/// Value would be 1

var WI
/// Value would be 1 

/// forgive me, I am a bit rusty with array's

Upvotes: 3

Views: 102

Answers (2)

Jean-Luc-Picard
Jean-Luc-Picard

Reputation: 31

Thanks to "Sterling Archer"... This is solved. Fiddle: http://jsfiddle.net/30bdf7h2/48/

// LIST

var locations = [{
  "name": "Costco",
  "city": "San Francisco",
  "state": "CA",
  "zip": "75201",
}, {
  "name": "Safeway",
  "city": "Appleton",
  "state": "WI",
  "zip": "90210",
}, {
  "name": "Foodmart",
  "city": "Orlando",
  "state": "FL",
  "zip": "90210",
}, {
  "name": "Trader Joes",
  "city": "Concord",
  "state": "CA",
  "zip": "90210",
}];

var states = {};
locations.forEach(obj => {
  if (states[obj.state]) states[obj.state]++;
  else states[obj.state] = 1;
});

var countForCA = states["CA"];

magic();
function magic() {
  document.getElementById("state_total").innerHTML = "CA Count: "+countForCA;
  document.getElementById("array_total").innerHTML = "Array Total: " + locations.length;
}

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22425

Using a simple loop, you can do this. (This uses ES6 arrow function syntax, and let. Easily replaced by var and anonymous function syntax for older browser compatibility)

let states = {};

locations.forEach(obj => {
    if (states[obj.state]) states[obj.state]++;
    else states[obj.state] = 1;
});

This loops over the array, checks to see if an entry exists in your counter object, and if it does, increment the count, otherwise add the entry and set it to 1.

Note that I used an object to store the counts, instead of individual variables. It's less messy and easier indexing this way.

Upvotes: 6

Related Questions