VividD
VividD

Reputation: 10536

Counting instances with same value

For a project, I need to do some data manipulation in JavaScript.

I need to convert this object:

[
        {"source":"stkbl0001","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0002","target":"stkbl0005"},
        {"source":"stkbl0003","target":"stkbl0005"},
        {"source":"stkbl0004","target":"stkbl0005"},
        {"source":"stkbl0004","target":"stkbl0005"}
]

to this object:

[
    {"source":"stkbl0001","target":"stkbl0005","value":1},
    {"source":"stkbl0002","target":"stkbl0005","value":5},
    {"source":"stkbl0003","target":"stkbl0005","value":1},
    {"source":"stkbl0004","target":"stkbl0005","value":2}
]

(notice that some elements in the first object are same and new field value contains number of repeats)

Basically, I need to detect and count multiple instances, and to create new field value that contains number of instances.

How do I do that?

Upvotes: 0

Views: 45

Answers (1)

Daniel Weiner
Daniel Weiner

Reputation: 1904

You can keep track with an object:

var obj = {};
var result = [];

for (var i = 0; i < arr.length; i++) {
  var item = arr[i],
      key = item.source + '-' + item.target;
  if (obj.hasOwnProperty(key)) obj[key].value++;
  else {
     obj[key] = item;
     item.value = 1;
  }
}

for (var prop in obj) {
  result.push(obj[prop]);
}

In this example, arr is assumed to be your original array, and result is your resulting array.

result will end up being an array of objects that have unique combinations of source and target properties, and value will be the number that those combinations were encountered.

Upvotes: 1

Related Questions