corry corry - 3 months ago 9
Javascript Question

Slice properties from objects and counting

Is it possible to slice single property from array of objects like

[{"name":"Bryan","id":016, "counter":0}, {"name":"John","id":04, "counter":2}, {"name":"Alicia","id":07, "counter":6}, {"name":"Jenny","id":015, "counter":9}, {"name":"Bryan","id":016, "counter":0}, {"name":"Jenny","id":015, "counter":9}, {"name":"John","id":04, "counter":2}, {"name":"Jenny" ,"id":015, "counter":9}];


I'm trying to slice
name
from every object and count number of the same elements (there are 3 objects with name Jenny) in order to achieve the following structure:

[{"name":"Bryan","Number":2},
{"name":"John","Number":2},
{"name":"Alicia","Number":1},
{"name":"Jenny","Number":3}]

Answer

You could use a hash table as a reference to the counted names.

var data = [{ name: "Bryan", id: "016", counter: 0 }, { name: "John", id: "04", counter: 2 }, { name: "Alicia", id: "07", counter: 6 }, { name: "Jenny", id: "015", counter: 9 }, { name: "Bryan", id: "016", counter: 0 }, { name: "Jenny", id: "015", counter: 9 }, { name: "John", id: "04", counter: 2 }, { name: "Jenny", id: "015", counter: 9 }],
    grouped = [];

data.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name, Number: 0 };
        grouped.push(this[a.name]);
    }
    this[a.name].Number++;
}, Object.create(null));

console.log(grouped);

Comments