1

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

3 Answers 3

2

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'))

Sign up to request clarification or add additional context in comments.

6 Comments

"I want to count each value for each property"
this is very good, but what about a big array without knowing the values? is this possible to count each value without knowing it? just count the occurrence of each value in a property
@m7majidi Yes, and that exact question is why I flagged this as a duplicate. Check out the question I linked in the comment. This question has been asked numerous times and is a matter of a simple google search.
edited. @mhodges I was not aware about duplicates, downvoting is still not needed because this isn't a duplicate until it is a duplicate.
@Hitmands I downvoted because it doesn't answer the OP's question of "I want to count each value for each property", but I think downvoting because of an obvious duplicate would not be inappropriate. You've been around long enough to know that this question has been asked before.
|
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.