问题
i need to count the number of occurrences of values in jsonArray items in javascript.
consider this as my jsonArray:
{"name":"jack","age":23},
{"name":"john","age":20},
{"name":"alison","age":23},
{"name":"steve","age":25},
.
.
.
now for example i need to know how many times each age is repeated in this array, i want to count each value for each property, i mean i need a result like this :
name : {"jack" : 2,"james" : 10,"john" : 1,....}
age : {"23":10,"20":15,"25":2,....}
what is the simplest way to achieve this?
EDIT : my array is very big and i don't want to call count function for each value. i want a code to count each value repeat times.
回答1:
you can have a look at Array.prototype.reduce
function mapToProp(data, prop) {
return data
.reduce((res, item) => Object
.assign(res, {
[item[prop]]: 1 + (res[item[prop]] || 0)
}), Object.create(null))
;
}
const data = [
{"name": "jack", "age": 23},
{"name": "john", "age": 20},
{"name": "alison", "age": 23},
{"name": "steve", "age": 25}
];
console.log('mapAndCountByAge', mapToProp(data, 'age'))
回答2:
You could use an object, where the keys and the values are used as property for the count.
var array = [{ name: "jack", age:23 }, { 'name': "john", age: 20 }, { name: "alison", age: 23 }, { name: "steve", age: 25 }],
result = {};
array.forEach(function (o) {
Object.keys(o).forEach(function (k) {
result[k] = result[k] || {};
result[k][o[k]] = (result[k][o[k]] || 0) + 1;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
回答3:
Not as elegant as Nina's and Hitmands' answers, but this is easier to understand for beginners (in case any beginner is reading this).
var jsonArray = [
{"name": "John", "age": 20},
{"name": "John", "age": 21},
{"name": "Doe", "age": 21},
{"name": "Doe", "age": 23},
{"name": "Doe", "age": 20},
];
var names = [],
ages = [];
// separate name data and age data into respective array
// only need to access the original data once
jsonArray.forEach(function(val){
names.push(val['name']);
ages.push(val['age']);
});
function aggregate(array){
var obj = {};
array.forEach(function(val){
if (!obj[val])
// create new property if property is not found
obj[val] = 1;
else
// increment matched property by 1
obj[val]++;
});
return JSON.stringify(obj);
}
console.log("Names: " + aggregate(names));
console.log("Ages: " + aggregate(ages));
In my opinion, Nina has the best answer here.
EDIT
In fact, when presented with large dataset (as OP stated that "the array is very big"), this method is about 45% faster than Nina's answer and about 81% faster than Hitmand's answer according to jsben.ch. I don't know why though.
来源:https://stackoverflow.com/questions/44829459/javascript-count-number-values-repeated-in-a-jsonarray-items