简体   繁体   中英

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

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM